 It's not about Java, it's not about abstract, factory, factory, factories. This is, again, pretty simple stuff. It's a very simple pattern and basically in backbone apps, what it means is that you pass in your dependencies to your constructor objects and then you check for them and you throw errors if they're not present. Essentially, what this allows you to do is enforce the constraints that are built in inherent to your application so that later on when you rely on these things that are assigned to you as instance properties like this collection and this example, that you know they're going to be there. You're creating a contract inside your code that's enforced and it will throw errors. The benefit here is that it's easy to test. Thank you for presenting on testing earlier. This was something that I was going to have to kind of pause and explain, but this is using Jasmine or Voco with Chai. It's very easy to check that if you try to instantiate this class without a, you try to instantiate this class without your actual dependency in there. It's going to throw, it's going to error. You can check that readily and easily. Keep trying to go to that slide. It's very easy to understand just from looking at an initialized method what is required for a given class instance to work and to function. You're going to be showing some more code throughout the rest of this talk to really show what exactly this means and what the benefits are. You're enforcing your applications or constraints by contract. If you're depending on another class, just make it explicit that you're doing so. Throw errors if your dependencies aren't met and pass dependencies as options into your constructors. It's essentially making sure that your application knows how it's going to run. Back-on apps tend to start small and then they get really, really large and really, really big. They get happening enormous. It can be really frustrating over time when you're working on larger and larger applications that you have classes that you don't know how to use, that you don't have a clear pattern for using. We're going to be talking about some of the ways to organize things a little bit better and some of the pitfalls that you can run into. My favorite line from the back-on documentation and what I tell people when I'm working with teams that are when I'm consulting with them on back-on apps is that there's more than one way to do it. If you've done this differently or if you have different opinions about that, that's great. One of the benefits of back-on is that it's very flexible and so just keep that in mind. Let's take one step back before we move in further. Back-on apps present two distinct types of organizational problems. The first is constructors. Constructors are the literal plans of your application. They are created, they're made to create instances and unless you're assigning static class methods to them, they're really not that useful on their own until you actually do something with them, until you create an instance. Instances, this is your application when it's running. This is where the state of your application lives. You essentially really care about when you're debugging your app, when you're actually putting everything together, making all these constructors come to life into an application. How do you go about organizing these two things? There's the global namespace that you can use. It's very easy to tack things into it. Creating globals in JavaScript is almost too easy to do. Then there are module systems that you can use to organize your constructors. I know. Let's use global variables to organize all of these things. This is a really common pattern that most people have used before. I call it the single namespace blues. You end up creating these ad hoc standards and you have a lot of this boilerplate code of checking that if this app exists, make sure that all the internal structure is there before you move on. But then you still have this problem where you're creating classes and creating naming conventions that don't necessarily have to line up to file names. It gets confusing when eventually you go to start your app in this final snippet. You actually go to start your application and you also have to attach it to the global namespace so that you can access it through the command line. The problem is that this is brittle. Relying on the global namespace like this, it's brittle. It's like this woman trying to eat a taco. It's just not working. Really outside of the rails asset pipeline, which is based on directives that help you concatenate files. This is really hard to do. It's not very portable when you have to rely on a concatenation script to run to slap all your JavaScript together into one bundle or you're dumping dozens and dozens of script tags into an HTML document to serve your application. Even when that's done programmatically like it is in the asset pipeline, it can be brittle. It can be unruly. Again, this is about ad hoc conventions that you have to put together to figure out how to do this stuff. Globals go against the grain of modularity. Dave Herman put this really well. This is in his book, Effective JavaScript. Globals also create this net effect of an intergalactic wormhole in your application. Globals can change at any given time and relying on their presence either for passing constructors around or passing instances around is problematic. It's something that's very easy to do and in the simple cases like in to do MVC, it's shown as kind of like this only way, the lingua franca of how you do this. It really just doesn't apply to building large applications. There's nothing actually wrong with this. There are just more expressive patterns for doing this. I'm going to talk about modules. Many people have opinions about modules. Backbone takes a stance of kind of finger in the ear's neutrality towards modules and that it just attaches itself to the global namespace and then it lets you do what you want with it, but is common JS compatible and you can shim it with required JS. Modules can help organize your constructors. If a backbone app is made up of all of these different constructors that you throw together when you create instances, you need to have means of organizing those and tying that into the file system so that you can use folders to separate these files, use the actual names, good naming conventions. It makes it so that it can be very clear when you look at an app that's using either common JS or required JS to see what an individual module depends on. That's one type of dependency injection. It's very important for being able to organize apps effectively. Dependency injection, and this is the kind of manual dependency injection that we saw a little bit of earlier and we'll be seeing more of in a second. Dependency injection helps organize the instances of your application. The actual code while it's running, you can actually have these two dependency graphs. One of all the dependencies based on your constructors, what your constructors need to create new objects, and then two, your instances. What your instances will rely on to listen to events and to call methods and to have models and render views and kind of have all of these chained reactions in your application. Keeping your module system and instant management separate divides and reduces the cognitive load of your app. This concept of cognitive load means that every time you sit down to code, every time you're going to write something in your application, you have to think about what you're doing. You have to open the files. You have to find the relevant class to what you're writing. You have to create new things. The less you have to think about doing that, the more time you can actually spend writing code and fixing defects or creating more features. Keeping these two systems separate and distinct is really, really important. You might be saying, why not just use require? I'm sure Tim Braynian is asking this right now. Why not just use require? Require is, again, it's completely valid, but the same types of problems come up when you're using one system to manage these two different types of things. You don't know whether you're passing around your application instance, which is a singleton that you're not supposed to modify, or whether you're passing around a constructor that's meant to be used with a new keyword. I've just always thought that using one thing to manage two things ends up being confusing in the long run. I talked about these two types of dependency graphs. What's actually cool is that there are visualizations that you can come up with to really express how these things look when your application is running. The first that we'll take a look at are the constructors. Like I said, these are the blueprints of your application. Then what's a little bit harder to imagine, and what we're going to have to use our imaginations for, is the instances of your app, the things that actually compose your app while it's running. It's a hurricane of awesomeness. This is actually from an app that we wrote earlier this year. These are all of the dependencies from RequireJS. You can see everything is circling around. The templates are actually raining the whole center of the application instance, and then there's a config module that lifts off on its own. That's just static and exposes a global variable. This gives you a good idea of, from the actual constructor dependency chains, what your app is actually doing, how those relationships can be expressed. We actually ran this on a bunch of different apps, and they actually all end up looking very similar in that we have several modules that are tightly dependent on one another, and then a whole bunch of modules sprouting off from the side, whether they be templates or views or helpers, or these one-off methods, and again, config sitting off here on the side. The first type of these kind of visualizations is really easy to make programmatically, assuming that you're using modules. If you're just using global variables to dump everything into, you're not going to be able to really get this easily. I generated those with a cool tool called Dependo, and so that will take a ComJS or an AMD project and kind of make this really cool D3 visualization. It would have like the live visualizations in here, but they're kind of crashing the browser. There are too many modules. The Instance dependency graph is a bit more ephemeral, and you kind of have to run your application to see it, and actually one of the best ways to really get into how your app is running when you visualize this is to expose part of your application to the console, to expose a global variable, and then be able to tree into your application, say app.model, app.collection, app.collection.view, or whatever your internal structure is. The console is actually a really powerful prototyping tool that, aside from test-driven development and actually just running things in the browser, you can get really far by just having a single global variable exposed that your application, that your primary application instance attaches to, and then that you can go in and kind of check that object structure and ensure that you know the expected JSON is what you want it to be at a given time. Again, this isn't like a complete substitute for like breakpoint debugging, but it's a very, very important concept that actually can kind of get ignored or missed sometimes. So let's talk about refactoring a little bit. So refactoring just for a refresher is altering the structure of your application while keeping the behavior intact. And so oftentimes this is moving re-named files, this is changing method names, this is, you know, kind of moving things into better organized patterns, and refactoring without tests is really just changing stuff. So going back into the kind of the test-driven development talk from earlier, it's really, really important to have a baseline of both unit tests and functional integration tests. If you're going to take refactoring seriously and not just have it be a series of arbitrary changes that you're making that may or may not break your application and cause you a lot of headache. So this moves into some patterns for applications. And Jeremy spent a lot of time this morning talking about kind of different patterns in backbone. And you know, this is going to be touching on this, touching on some of these a little bit, a little bit more, and you know kind of throwing in some opinion and some experience-based opinions in there. So we'll be talking about application views, the single point of entry to access instances, which I talked about, you know, exposing your application to the global namespace and being able to go in and explore that, you know, the object tree of instances that you've created, and talking a little bit about having views that are long-lived. And this is something that, you know, you can, you know, Jeremy made a very good point earlier today talking about, you know, applications that are meant to be running for a very, very long time. You know, you can kind of leave your browser session open for weeks and come back to it at any given point. And, you know, I feel like a lot of, there's a lot of, you know, kind of hair pulling that happens when, you know, you try to, are too aggressive with tearing applications, with tearing things down. And, you know, there are some cases where you can just have long-lived views that are really just hidden and that you come back to. Really depends on the nature of your application. And so, like, you know, I see the kind of, you know, I see, you know, kind of chasing down those garbage collection wins of, you know, tearing down big sections of your application as an optimization step. And it's something that, you know, you really don't need to start with the assumption that every view that you create is going to eventually call destroyed. You can very well do that and listen to and stop listening makes that a lot easier. But you're going to have a much easier life if you, you know, treat some of the larger sections of your application as things that will be long-lived. So, I'll zoom in here again. So, this is a pattern, this is, you know, a code that I pulled from an application that is showing, you know, just a small snippet of what you can do with, you know, some of this basic dependency injection. And we'll talk about, you know, patterns for enforcing this a little later on. And so, this is a view that attaches itself to the body. And it fires up a collection. This is assuming, again, that, you know, a media collection and user model are both things that, you know, these constructors were accessing by way of RefireJS or CommonJS. So, you know, this is pretty, this is pretty standard. But what's happening here when we're looking at the, when we're looking at where we create this injector object, and we put a reference, a reference to this actual class. Just by saying, you know, injector.app is this, and reference to this collection. And then that actually gets shared and inherited through all of these different views and what, and around. And so, what these individual views are going to do is actually apply that pattern we saw earlier of, within the, within the actual initialize method, they'll expect that a collection is going to be created and they'll throw if it's not there. They'll expect to be passed an application instance, because perhaps they're using that application instance as their applications event bus. You know, instead of using the global backbone events or instead of the, instead of, you know, relying on some other system or, you know, directly calling methods on these other, on these other classes that they might be, that they might have a reference to. Using that application, the application view itself as their, you know, kind of main, as that central hub inside these dependencies of, of objects. And so, and then, you know, finally we'll, we'll actually attach this, attach this to the window and call history start and then, you know, assuming that our router is going to take over from there and, you know, start calling methods either directly on the application or trigger, or trigger an event for some of these views to do something. The instances have a reference to the application view if they need it. There's nothing saying that, you know, we have to pass that to them, but this was from an application where it was a pretty small surface area and all these views needed to reference this, this, this main application view. The application view is doing other stuff later on in the file. So this is normally almost always an instance property. So again, you know, if we tree into that from the, from the console and our browser, and most browsers have, even IE has a, has a serviceable console. So there's no excuse for, for not doing this or for not, at least being able to look at your application while it's running. And so they're referenced by, by properties on the instance that we will attach directly. And again, we'll look at some patterns for doing this in a moment. And the circular references here are totally fine. They, Javascript optimizes, optimizes for this and we can just leave this slide up for the next 22 minutes. So Javascript optimizes for this and Ron Swanson mustache here is really just something about that gift. So, so the app instance gets pushed down to every object that depends on it as well as that, is that collection, that collection instance. So this is a great pattern for, you know, showing really how you can share a collection or share a model between multiple different views. And in essence, this is dependency in injection, but what makes it different than just, you know, passing these things around is having a clear pattern to enforce it. So there's some simple sugar. And again, there are a million ways of doing this. This is just one, but we can, you know, create a little enforced dependency, wherein we take a, we take a given, a given model or viewer collection and class of the K and we filter its dependencies and we make sure that we make sure that the dependencies are there in the options half hash that will forward to this and we'll throw an error if they're not there. And then the second part of the filter is making sure that they're not already present on the, on the class. So like model and collection and several other magic properties get, get mixed in. I can never keep track of what they are between, between classes. So just, just having something that checks to make sure that they're there and then this is actually one of my favorite lines from the backbone source. And this is how backbone actually mixes in its constructor, the options that you pass to a constructor. I think this is a Brad Dunbar line. And when I first saw this, it was like, to my narrow mind explosion, kind of really turned my head on, on its side. But you pick things out of the option, out of the options hash, you pick this array of dependencies out and then extend it back into the class. Pretty cool if you have never done that before, never seen that. And then so, you know, the way to actually apply this, zoom in here a little bit more, the way to actually apply this is in an initialized method to just call it enforce dependencies and pass, pass the reference to the class itself and the options hash that it gets as well as the dependencies that it would actually have. And so you could foresee being able to actually mix this in to happen on every constructor to look for these dependencies perhaps is an array of expected dependencies that are, that are a property directly on the prototype. And there are a lot of, a lot of different ways to slice this, but what it breaks down to is that you have a means of enforcing what your instances require and your application won't work if you use these improperly which if you've worked on a team with any number of developers, you know, documentation is, seems difficult to write and there's kind of institutional knowledge that people will miss and, you know, having a class that clearly throws an error when you're misusing it it keeps you, it keeps you honest in it and it also provides a really easy path for testing these things. So tests are what enforce the contract of dependencies and without tests for this, yeah, you'll see errors in the console but, you know, those errors are really meant for developers to write a test against to make sure that this class, this class's behavior is going to do exactly what you want it to. And I would rather have an application that only tests its dependencies exist and that each constructor can properly create the instance that you expected to than enough that retests methods from backbone underscore and jQuery endlessly, you know, kind of the heavier side of functional testing that can make its way into unit tests when you're, you know, checking that dollar.html still works, it does. It won't change. And so, again, we'll take we'll take a little bit closer look at this at the same test and, so assert.throws is something that comes with chai. Most every assertion line every comes with some ability to check that a check above function frozen error. So, again, we'll just describe playlist view and we'll say itch error if it's created without a collection. In the same way that you can create a helper or a mix in for, you know, having for attaching these dependencies, you can create loops in your test suite and make sure that if especially if you're exposing the what the what the name dependencies would be as a property on the prototype, you'd be able to test these things very easily and have a test suite that has actually, you know, describes your app pretty well and so the this part is just a regular expression that runs against the the message coming out of the coming out of the error that was thrown. So, please, please, please use Synon.js for spies and stubs. Even if you're using Jasmine, it's probably a good idea. The spies that come in Jasmine they're they're serviceable but Synon offers offers a lot more in my opinion and seriously just just use it, look at it. I'm probably not going to be the last person that mentions it today or tomorrow. So, yeah, I think we've talked about this a little bit already but apps should be accessible to the outside world from the from the console and really shouldn't underestimate it as a prototype as a prototyping tool. How frustrating is it if you have to use breakpoint debugging and, you know, go in and inspect your code just to see, you know, one little change or see, you know, what the what the given value of something is. I for all the time that I spend developing backbone applications much of that is spent in the console and it's something just use it and expose your app to the outside world. Give it one place to live. Don't spray a whole bunch of global variables because that's also kind of defeating the purpose but having a means of crawling back into your application after you've after you've kickstarted it is extremely important. And again, even IE has a somewhat usable console. So the last thing that that this kind of ties into are the solid design principles and they've already been mentioned today and, you know, I'm going to mention them again because I think that, you know, a lot of these things are, you know, like Jeremy said, you know, OOP 101 but they're not necessarily JavaScript 101 and so, you know, JavaScript, if you're starting like many of us with a background using jQuery to or prototype to enhance, you know, HTML documents, these things aren't necessarily obvious and I think that one of the most interesting things about backbone is that it can really unlock the kind of next step in writing applications and writing well-structured applications. And so the solid design principles if the Wikipedia page covers it quite well we'll kind of get a walking tour of what they are but if you only write code following these five rules solid as an acronym if you only write code following these five rules you'll actually write apps that are pretty clear and reasonably and can be reasonably well understood and these are the building blocks of object-oriented design patterns so whenever, you know, again, if you learn these and that, you know, you hear Adi Asmani talking about the mediator pattern you'll kind of understand that it's just a combination of these couple things and that, you know, all the kind of design patterns lingo that gets tossed around is really just a couple of simple concepts, you know, shaken up and mixed up in different ways. So just going through top to bottom so the single responsibility principle dictates that a class should only have a single responsibility and that can get extended to backbone applications and saying that method should only be responsible for one thing and as soon as it's responsible for two things you should split that up to create an interface that, an interface to that it helps its unit testing and it just makes your code more sane. Anytime that you have, you know, a single method even if it's like an initialized method that's meant to do a lot if it's a yard long and takes, you know, two, you know, vertical monitors to see everything there's probably an opportunity to refactor that there's probably an opportunity to write tests around that and to actually break this up in a way that's structured and organized. So the open-close principle software entities should be open for extension but closed for modification. This is essentially what tells you that you shouldn't go around monkeying with browser natives and, you know, they're just kind of overwriting prototypes in a way that isn't forward thinking is a bad thing. Backbone provides a very easy mechanism called Extend to do this. It's used just about everywhere and, you know, you should definitely, if you do have a need of customization, you should definitely be extending it rather than just, you know, tacking stuff on to backbone model that prototype. So LISCOP substitution. This one's a little bit a little bit more more heady but objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. So essentially it means that you shouldn't be changing things so much that your extensions look nothing like their parents. So, you know, many times in tests even with, you know, enforcing dependency injection you can get away with, you know, something expects a model. It's not necessarily expecting the model that it's passed but perhaps a generic model. So if you're thinking about, you know, well, I need to mock this given state but it's really just a collection and it's really just, you know, has the, you know, it's using fetch and it's using, you know, event listener methods. You can pass a generic collection around and backbone is actually with its extend method gives you a built-in way of doing this pretty easily. Obviously, this one's probably the easiest to break because as soon as you start writing custom methods on your models or collections you can and then using them in other classes you can get into trouble with this. But if you kind of follow these other steps LISCOP substitutions happens pretty readily. So interface segregation. I've touched on this a little bit with single responsibility but again, many client-specific interfaces are better than one general-purpose interface. So even if you are creating one general-purpose interface that's branching out and calling a bunch of, you know, a bunch of individual methods it's something that your code will always be better if you just make your functions responsible for less and separating and separating those interfaces up into logical groupings is going to give you a lot of net benefit. And finally, dependency inversion and this is really what ties this all back into dependency injection and this is that one should depend on abstractions do not depend do not depend on concretions. So basically that means that there's this thing that you can do where you flip over your your dependencies and instead of, you know, relying on a bunch of external APIs relying on the you know, on the events that those that those APIs generate this is something that's part of backbone with the with the event with the event system that that's there in in everything so you don't have to you know, rely on pulling a model to see its changes you can listen to you can listen to change events and similarly you can with with dependency injection you can you can inject in different versions where you can inject in different instances to your you know, to your views or to your models and listen to listen to events on them and that's something that's you know, can be done generically and you know, especially with listen to without much without much overhead or without you know, permanent damage being done because there's a way of backing out of that moving away from it and so this is a John John K. Paul's talk tomorrow is actually touches on touches on this a little bit so you know, definitely there's some really cool stuff that you can do with jQuery plugins and and kind of external API's in general especially in the context of backbone that gives you these kind of rich tools to make interfaces that are easy to follow so again, talking about modules a little bit Dominic Danapola has talk yes, six is nine the link is here it's definitely worth checking out modules are coming they're imminent and someday we'll actually get to use them natively without having to transpile into AMD or commonJS or UMD or whatever the new flavor is going to be in six months but modules are modules are really cool and you should definitely use them they've picked up some steam they really make applications easier to write they the vote is out of whether they made libraries easier to maintain depends on the size for something like backbone where it comfortably fits into into one file there's not there's probably not much not much to be gained by breaking that up you know, to the end of the earth but certainly your applications when you have tens of thousands of lines of code you should be using a module system please I implore you fight for this with your management make sure that you know you have the time and the and you know all the resources that you need to refactor into using some type of module system I think that it's extremely important and again not having to not having to think about managing your constructors leaves more time for writing your app and writing tests for your app too and so just about just about wrapping up but a brief aside starts with with a bold statement components are the future and I think that you know web components Tim Brayman is going to be talking a little bit about this tomorrow web components are something that represent really interesting patterns for you know how we can parse up our applications and how we can focus on writing things that are truly modular and modular applications I think have the best chance at being future proof ORAJS is an Adios Monte project it's really it offers a really cool interesting solution for this so ORA components are written in JavaScript so they're ready to use now you don't have to use polyfills or you don't have to grok everything that Angular is doing to to use these it's framework neutral so they actually you know have examples of ORA components working with Backbone working with Ember working with Angular and they don't make you lock your logic in the markup so it's definitely just kind of food for thought something to something to check out if you're interested in you know kind of looking at something that helps you write code that's modular Twitter has something similar called Flight but ORA is kind of a little bit more forward thinking and so a bonus this happens to me all the time initialize will never work if it's spelled wrong I don't know if there's anything we could like Jeremy if we could do in the library to like fix this but yeah initialize won't work if you spell like that or the many permutations that I often fat finger so I'm writing a book called Backbone JS in Action for Man in Collocations it's it's in Beeps right now so that means you can take a look at the first four chapters and give me feedback in the forums for what you like what you hate what you want to see there is a 45% off coupon the very very easy to remember MLBB JS CEO okay I don't know why the codes are so obtuse but but yeah so so please check that out and I definitely am trying to make it you know good another good resource in the cavalcade of backbone of things to learn backbone so questions other than questions about this slide any you made reference to exposing your application to the window essentially attaching it to the window are there any benefits to that other than you get to access it from the console so I think that's that's definitely that's definitely the primary benefit I mean there's yeah that's a good question so probably so probably not if you're unless you're you know kind of writing a backbone application that you know exposes a plugin of some of some sort you know it's really primarily the means for debugging and kind of being easier easier to get out without having to well there's not really any other way to get at it if you're not exposing it to the window hey Sam you um I really like the parts out you know checking your dependencies you know adhering to a contract there but a check for existence seems like an awfully weak contract I mean do you have any thoughts on feature detection or you know just inspecting or further tests of those those dependencies you're detecting yeah so you can definitely you can definitely go much further much further down that road and you know check for the check for the individual methods that you're going to use or check that the that the properties that are are there you know in these in the cases that I showed you know it's essentially checking the um you know checking checking for for existence but you can easily do instance of and check that you know this thing actually a model this thing that you're passing is actually you know of a certain type so so yes there's a there's definitely a lot more that you can a lot more that you can that you can do do you have any thoughts on the AngularJS dependency injection where it actually does a lot of magic and parses the method signature yes they do think that it's magic um yeah and you know anglers anglers take on dependency injection is definitely of the more complex variety you know I haven't written a ton of applications using Angular I've really only done the kind of boilerplate Hello Worldly type stuff so probably not the best person to to speak to that but I do know that it is you know kind of one of the concepts that they lead off with in terms of you know being able to like change the argument order in entering directives or you know using the the scope key where it will detect and you know pass it in wherever you you use it so I mean that's definitely a more complex and I think that building something like that into a back of an application would probably just take a lot of code to do but certainly certainly in the same pain thanks everybody