Closures, Private & Methods
Published 9/2/2015
Today, we talk about closures and private object methods.
- Spec.fm
- Closures in JavaScript (Mozilla)
- Private methods in Ruby (documentation)
- Private :attr_accessor
- Private members in Java
- Closures: Elixir vs. Ruby vs. JavaScript
Today's episode is brought to you by Spec.fm - brand new podcasts and content for developers and designers!
Transcript (Generated by OpenAI Whisper)
Hey everyone and welcome to Developer Tea. My name is Jonathan Cutrell and today I'm going to be talking to you about closures. How closures can be compared to objects in object oriented programming. Specifically we'll talk about it with relation to JavaScript so that most people will understand kind of how JavaScript closures work. If you've worked with JavaScript you have probably encountered closures whether you know it or not. Today's episode is brought to you by spec. Spec is the network that I helped create with brand and Brian. And I guess we are still creating it. Spec.fm is where you can find all of the shows that are a part of spec including design details and little bites of cocoa. Tons of really interesting content that is constantly coming out of this group of people. Spec.fm make sure you check it out. Of course the show notes for Developer Teacan be found there and there's a player where you can play all episodes of Developer Tea. And we're constantly releasing new features on spec.fm so make sure you go and check it out on a regular basis spec.fm. So closures. Closures are a kind of a black box if you haven't studied them a little bit. And I've done some research to prepare for this episode to talk about closures because I think they are misunderstood by a lot of programmers. Specifically closures as they relate to languages that aren't necessarily considered object oriented or more specifically languages that don't have a class a class constructor in them necessarily. Now I'm going to go ahead and include JavaScript in this discussion because JavaScript doesn't technically have classes yet. And the question really is still up in the air about how that is going to play out whether or not the class structure is going to be a thin layer over the top of the prototype structure or not. So we're going to talk about JavaScript as if it doesn't have classes today because in the ES5 it doesn't have classes. ES6 and beyond there is a class constructor for JavaScript but we don't know entirely what that's going to end up looking like. So for the purposes of today's episode we are going to consider JavaScript a good example of a language that implements closures and in fact closures are used all over the place in JavaScript libraries that you most likely are using today. So JavaScript is a language that utilizes closures and probably will stay that way for quite a while even with class structures being introduced formally in the ES6 and beyond. So let's start with Mozilla's official definition of closure which you can find in the show notes at either spec.fm or Developer Tea. The definition is closures are functions that refer to independent or free variables. In other words the function defined in the closure remembers the environment in which it was created. So what does this mean? Well let's see you have an outer function we'll call this function a and inside of function a you have function B. Now inside of function a before you define function B you have created a few variables with the var keyword. Now in JavaScript the var keyword scopes those variables to whatever the current lexical scope is for that variable. We are outside of function B but we are inside of function a and we're creating variables basically what this means what is what a closure allows for is the outer variable closes those variables in and closes that function in and you have access to those variables that are defined in function a inside of function B. However you do not have access to the inner function B from outside of a and if you were to define a variable inside of function B then you do not have access to that variable inside of function a. This gets a little bit hairy gets a little bit difficult to understand but it comes down to the simple idea that the scope of a given function is passed into other function so nested functions can access the variables that are defined outside of those functions. What this allows you to do is create very interesting systems where scope is exploited in order to create the privacy of a given type of variable or perhaps the ability to create a function returning mechanism. For example you can imagine that that outer function a holds a function B inside of it but when you call a it returns B not that it returns the result of B but quite literally it returns the function B so calling a gives you access to the interior method of B without actually exposing B out to the world. And where this gets even more interesting is that inside of B you can return an even further nested function C for example so why does this matter well if you are paying attention as an object or in a programmer then you'll likely notice that this sounds a lot like private methods in Ruby for example you can define private methods by simply using the keyword private and then below that all the methods that you define there will be only a few. Only accessible inside of that class and in many ways these are two sides of the same coin if you come from a functional background then you accomplish this same idea of only allowing code to be called in certain places through closures and if you come from the object or in a background then you are likely to use something like private variables or private methods to accomplish the same goal so hopefully we've kind of covered this idea. That closures are in many ways quite similar to private methods or private variables and the idea that scope is important but what we really haven't talked about is why you would want to use such a thing why does why does a private method need to be created why not just make it all public why not allow all functions to be available at the top level when I first started out programming I thought this actually literally had to do with the security of your code that it would be easily penetrated. By some kind of hacker attack or something but that was totally wrong obviously this has nothing to do with security but has everything to do with usability and maintainability as a developer even more specifically having private methods and utilizing closures allows you as the developer to determine how things change and how they are accessed and modified by whatever other methods are used. This is a very simple practical example would be if you had a counter in JavaScript and you set your counter the current count to a variable inside of a function and perhaps you have bounds on that counter where you never want it to go below zero and you never want it to go above 10. With pure JavaScript you could simply reset that variable to a given number and of course you can easily set a variable to something outside of the bounds that you have defined in your program. If you instead set that variable inside of the scope of a function and then return functions that can modify that variable but only within the bounds that you have set. Now you have a controlled state where that variable will never be outside of those bounds so you could have an increment method inside of this scope that allows you to change the variable and because of closure scope you can only change that variable using that particular method that you've exposed by returning it. So this is a very simple example of this is if you are creating a class that has a few methods and each of those methods repeats the same three or four steps you may want to factor out those three or four steps into their own private method but that doesn't mean those three or four steps necessarily need to be called on their own outside of the context of the class that holds the methods that should be called on their own. The perfect example of when you would use private methods in your classes is when those methods only make sense in the context of another method particularly of another method within that same class. The same is true for JavaScript a lot of the time that we create variables that are accessible in a scope that they shouldn't be accessible in. In doubt it makes sense to create a function scope create that closure and give yourself that protective layer not only do closures kind of protect you from yourself of overriding data or perhaps accidentally setting state in the wrong way but they also make your code much easier to maintain because you aren't relying on global variables or implicit state and your methods are much smaller typically your functions end up being smaller. Much easier to tell what exactly is going on what is being read from where what is being written where I encourage you to look deeper into the idea of creating private versus publicly accessible variable scoping and function scoping or methods scoping learning about scope will change the way that you see the libraries that you use it will change the way that you write your own code. And if nothing else I hope that you start a conversation about closures about variable scoping and methods scoping with the people that you work with and perhaps with people that you talk to online start the conversation with me if you go to spec.fm slash slack you can join the Slack channel for the spec network and I'm in there the guys from design details are in there and there's a bunch of people who are ready and willing to talk about all these kinds of subjects go and check it out. Go and check it out spec.fm thank you again for listening to today's episode of Developer Teaif you have questions or thoughts you can send them to me at developertea@gmail.com there's also a contact form on DeveloperTea.com until next time enjoy your tea.