Design Patterns in JavaScript

Design Patterns in JavaScript

June 17th, 2016 / placed in Study. / Tags: , , .

Design Patterns

A design pattern is a reusable solution to prevent programming problems that occur frequently.

Design patterns are optimized, reusable solutions for the programming problems we encounter many times. A design pattern is like an template that you can implement in your software. It’s is not language-specific and can be used in almost every programming language. Another great advantage is that reusing these patterns helps to prevent issues that cause major problems but also helps code readability for other programmers familiar with design patterns so they can understand and work with the code easily. Therefore, programmers familiar with some of the most common design patterns can contribute widely on projects with much more ease.

Every developer strives to write maintainable, readable, and reusable code. It’s like playing with Lego: there’s a handful of different pieces you get to snap together however you want. Sometimes you make something cool, but most of the time you make crap. However, the longer you play, the better you get.

Studying Design Patterns is much like learning “how to build applications in a good way”. By studying these patterns we mostly read advice from other programmers that have been programming and creating applications for decades. They have distilled their most common solutions into simple, understandable pieces of knowledge with memorable names. One could see it like an apprenticeship for the digital-age: the elders are giving their best advice. You can take it and be ahead of the game, or ignore it and repeat all of their mistakes.

Categories of patterns

There are many patterns that are mainly focused on languages with the use of classes and objects. These are categorized in creational, structural and behavioral patterns. For this article I’ll explain the most common patterns used for JavaScript. There is no ‘ideal’ pattern to use as developers often use best judgment when deciding on the pattern, which is the best ‘fit’ for their needs.

The most common patterns used for JavaScript that I will explain are:

– Constructor Pattern
– Module Pattern
– Revealing Module Pattern

Constructor Pattern

In my previous article I already shortly introduced the constructor pattern. In many other Object-Oriented Programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. In JavaScript, almost everything is an object, and we’re most often interested in object constructors.

The three most common ways to create new objects in JavaScript are:

Object constructors are used to create specific types of objects. They prepare the object for use and accept arguments which a constructor can use to set the values of member properties and methods when the object is first created.

Different from other languages, JavaScript doesn’t work with classes. What is does support are special constructor functions that work with objects. When we prefix a call to a constructor function with the keyword “new”, we tell JavaScript we want the function to behave like a constructor and instantiate a new object with the members defined by that function you called. Inside a constructor, the keyword this references the new objects that’s created. A small recap below:

The sample above is a very simple version of the constructor pattern. However, it doest suffer from some problems. One is that makes inheritance difficult and the other is that function such as toString() are redefined for each of the new objects created using the Restaurant constructor. It would be better if we could share this function between all of the instances of the Restaurant type. Luckily we have a work around this limitation.

Constructor with Prototypes

Almost every object in JavaScript, functions included, contain a “prototype” object. When we tell a constructor to create an object, all the properties of the constructor’s prototype are then made available to the new object we create. So when we extend the example from above with the following:

Since we’re calling a new method in the prototype chain of Restaurant, we avoid redefining our prototype object. As a result, a single instance of toString() will now be shared between all of the Restaurant objects.

The Module Pattern

The module pattern is one of the most commonly used design patterns in JavaScript. This pattern was defined as a way to provide both private and public encapsulation fro the idea of JavaScript “classes”.  In addition, it focuses to reduces globally scoped variables to decrease the chances of collision with other code within an application. Some other JavaScript frameworks and library’s like jQuery, ExtJS and YUI also make use of the module design pattern. Local variables and functions defined inside your constructor become private members. The return method for your function returns an object that contains your public methods and variables.

Modules

Let’s have a look at a module and review what the following function concept does:

This declares an anonymous function, which calls itself immediately, also known as Immediately-Invoked-Function-Expessions (IIFE). The (); ensures that everything contained will be executed immediately.

Global Import

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist.

By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals. For example:

However, sometimes you don’t just want to use globals, but you want to declare them. We can do this by exporting them, using the anonymous function’s return value. This is considered the basic module pattern:

Private Methods and understanding return

JavaScript doesn’t strictly have private methods. However, we can create a working equivalent. Why would we want privacy in our code? Well, lets say we might be making server calls, posting sensitive data. Therefore private methods are anything you don’t want users, developers or hackers to be able to see or call outside the scope they’re in. So lets use the new scope Module to make an inaccessible method outside of that scope:

If we now try to call privateMethod anywhere outside of our Module, we will get an error. Which is exactly what we want because we don’t want anyone to be able to call our methods. Especially methods that could manipulate data going back and forth to some server.

Typical Modules use return and return an Object to the Module, therefore the methods bound to this Object will be accessible from the Module’s namespace. The next example will give clarification on how public and private methods are being handled.

As you can see in the example above, we can only access privateMethod() within our return. If we would try to access it anywhere else, we would receive either undefined or an error.

To start a module pattern, it’s better to define a name in the global namespace to which u attach the different modules. Addy Osmani created a nice overview of the different options like so:

You’ll commonly see developers using Option 1, however Options 3 and 5 may be considered more thorough and Option 4 is considered a good best-practice. From there, u can have the following Module Pattern structure like this:

You may have noticed the _ before our private methods and properties. Because JavaScript does not have a private keyword its common to prefix private properties with an underscore.This way, everything outside your return statement is private. If you want to access the module from outside, you simply call myApp.Module.tellMyName(“is my name”);. We can access the public methods, but not the private. Only the public vars and functions have access to the private methods.

The Revealing Module Pattern

We’ve looked at the Module Pattern, but now lets talk about it’s famous big brother the “revealing” module design pattern, in which we reveal public pointers to methods inside the Module’s scope. This can create a really nice code management system in which you can clearly see and define which methods are shipped back to the Module, although it looks like the previous, it has the following structure:

The revealing pattern is much more clearer and declarative. Especially for bigger JavaScript Modules this pattern helps out a lot more.

So, if we make some private methods, how do we call them? We can simply invoke private functions through our public methods. For example:

We’re not just limited to methods, we can access Objects, Arrays, anything!

I hope you enjoyed this article about some common design patterns. My goal was to build up knowledge about design patterns used in JavaScript. Building applications this way really eases up on you by providing more structure and clearer code. Developing with design patterns provides is less clutter in the global namespace and it’s easier to get other developers on board when building big applications because of readability and reusable code.

If you’ve enjoyed this article, then don’t forget to read my previous post about JavaScript OOP and Prototype-based OOP!

Terug