Saturday, September 13, 2014

JavaScript Patterns: IIEF - Immediately Invoked Function Expression

The "createWorker" function is interesting. Because it creates in JavaScript what is known as a scope. 
The local variables that we've created inside the function, like "workCount", "task1" and "task2", they are only visible inside the function itself.



We can have function definitions nested inside of other functions in JavaScript. That’s how "task1" can point to a function that is inside of another function that we assigned to "createWorker".

This is great because "task1" can't be visible outside "createWorker". If we try invoke "task1" from the “worker” object.

We’ll get an error “undefined is not a function” on line 22.



That means something like “I don’t know what task1 is. I’ve got undefined for that and you decided to invoke it. That’s not gonna work”.

The only way we can invoke “task1” is because “createWorker” explicitly reference task1 in an object that is returned to the outside world.

But “task1” itself is inside the scope of “createWorker” and it’s not visible to the outside.
And these variables that we have outside of this function definition, including the variable “createWorker” and the variable “worker”, they are also outside the scope and unfortunately it is the global scope.

They are global variables because they are defined outside any other code, or any other function. If you are doing Software Development for a long time, you’ve probably heard that global variables are bad.

They easily become a source of confusion and bugs. But in JavaScript, global variable are beyond bad. They are evil.

Because JavaScript is a dynamically typed language, it’s very easy to overwrite a global variable defined by someone else and vice-versa. So we should try to avoid globals at all cost.


Is there a way to define all the code that we have, executing that code and achieving the same output without create any global variable?

The answer is yes. What if outside of “createWorker” we define a function called “program”, and program is going to wrap up not just “createWorker”, but also the code where we instantiate a “worker” and call “job1” and “job2”.



Right now, we only have one global variable called “program”.


But how do I get to zero global variables?

What if instead of declaring a variable “program” which will be global. What if we just took this function and at the very bottom of the function definition we just add it invoke itself.



There’s one little problem here. JavaScript doesn't particularly like this syntax.

It doesn't like to have an anonymous function that invokes itself. What we have to do is apply an extra left parenthesis before the keyword function and then have a corresponding close parenthesis at the end before the semi colon.



And what we have built is something called in JavaScript circles an Immediately Invoked Function Expression (IIFE).

It’s a function that has code inside that immediately invokes itself. Because all of that code is inside a function we're not creating any global variables.

All the variables that have been defined are local variables inside of that IIFE.


We should use IIFE to avoid create any global variables. A lot of JavaScript libraries use IIFE to control the scope of the variables, to build modules to provide encapsulation and most of all to avoid global variables.

Friday, September 12, 2014

JavaScript Patterns: Revealing Module Pattern

A good way of organizing our code is creating modules. A module can expose methods and data. But sometimes we don’t want to expose everything to the outside world.

In C# we can define our method or properties with access modifiers. And in JavaScript? Is there a way of doing this? The answer is yes.

Let’s see an example:

We start by creating a variable called worker and we will invoke a function called CreateWorker.


Once we will have the worker, we would like to perform different jobs (job1, job2).


And it’s not really important what the specific jobs are. Job1 could be calling a web service. Job2 could be applying a template to the data returned from the web service.

We are not really concerned about these details at this point. We will be focused in how we create this worker object that has 2 methods on it (job1 and job2).

We will create another variable called “createWorker”, this variable will point to a function that will return an object. That object would contain job1 and job2.



We could implement those functions in line, but we don’t want to do that. Instead we will create another to variables called "task1" and "task2" that will point to our functions.



This is how we expose "task1" and "task2" from our model.

The object literal syntax will allow us to expose those functions. We can say that "job1" points to "task1" and "job2" points to "task2". 



The top part is our private implementation details. We can even have private functions that would not be exposed from this object.


In the bottom part, when we return this object is where we define our public API. Here’s an object that have two methods, job1 and job2. No one really needs to know what is inside. But if we execute this code we’ll see that we are executing task1 and task2.

This is called “Revealing Module Pattern”. It’s called Module, because what we’ve done was encapsulate some code inside of a function. The general meaning of module in Computer Science and Software Development is “Collection of components or features that you can put together to perform some useful work”. We are creating a module in JavaScript by creating a function. Inside of that function we will build out some things that we can use and expose to the outside world.

And we can even have some private implementation details. If we create a variable called workCount that counts the number of times that task1 and task2 have been invoked.

That’s not something we want to expose to the outside world and allow them to manipulate it.

It’s just something that we want to use as an internal implementation detail, and perhaps each time this methods are invoked we will increment workCount and we will also print out the current value of workCount inside of each task.


If we run our code.



We can see its incrementing “workCount”. This is a good way to organise and isolate our code exposing only what needs to be exposed to the outside world.

Thursday, September 11, 2014

JavaScript Patterns: Functions as abstractions

How can we use functions to create abstractions?

We will create a variable called “work” and we want that variable to point to a function.
The purpose of this function is to abstract the way some sort of operation needs to be performed.
We need to do some work and we want to wrap that code inside of a function and assign it to a variable called “work”.
And the only work we’ll do here is something really simple.

“Working hard...” should appear in our console when we run this program.

And it works. So now let’s raise the level of abstraction.
Let’s create another variable called “doWork”. This one is going to be a function and it will take a parameter called “f”. “doWork” expects that “f” will be another function. Something that will be invoked.



If we invoke “doWork” and we pass in our “work” variable that happens to point to a function. All of this should still work and we should see “Working hard...” in our console.
Why we are doing this?
Why is that useful?
Why we don’t call the function “work” directly? Instead of creating another function to invoke “work”.
The all idea here is to provide some abstraction. Maybe “doWork” represents some routine that can add retry logic or that can add value perhaps by logging.
Log when “work” starts, when “work” ends, or even log errors while executing “work”.



This is just a common pattern used in JavaScript where we use the function as the basis for an abstraction.
Functions that do work. Functions that execute work. Passing functions to other functions.

Because “doWork” is a generic function that tells us when something is started or ended and also some error handling. And we can reuse it to perform different functions.