Pages

Showing posts with label JavaScriptDesignPatterns. Show all posts
Showing posts with label JavaScriptDesignPatterns. Show all posts

Friday, November 08, 2013

The Singleton Pattern

The Singleton Pattern got its name because it restricts instantiation of a class to a single object. This can be implemented by creating a method which creates an instance of the class if one doesn't exist, but returns the reference to the existing object, if already exists. Singletons are different from static classes as we can delay their initialization to a later point of time.

In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

The applicability of the Singleton pattern is described as follows:
  • There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • When the sole instance should be extensible by sub-classing, and clients should be able to use an extended instance without modifying their code.
Singletons are useful but they shouldn't be overused. The Singleton pattern is useful when exactly one object is needed to coordinate others across a system.

They're often an indication that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a code base. Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on.

Read more about Singleton Patterns ...

The Revealing Module Pattern

The Revealing Module Pattern, proposed by Christian Heilmann, is a slightly improved version of Module Pattern.  This makes coding easier as we don’t have to repeat the name of the main object when we wanted to call one public method from another or access public variables. Also, in the previous case (Module Pattern), we have to change the name of the private method also, if we need to make it public.

In this pattern, we would simply define all of our functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wished to reveal as public.

Advantages
  • More consistent syntax
  • Eases readability
Disadvantages
  • If a private function refers to a public function, that public function can't be overridden if a patch is necessary
  • Modules are more fragile
Read more about Revealing Module Patterns ...

The Module Pattern

Modules are an integral piece of any robust application's architecture and typically help in keeping the units of code for a project both cleanly separated and organized.

Different options for implementing modules in JavaScripts are:
  1. The Module pattern
  2. Object literal notation
  3. AMD modules
  4. CommonJS modules
  5. ECMAScript Harmony modules
Advantages of Module Patterns
  • Clean
  • Supports private data
Disadvantages of Module Patterns
  • As we access both public and private members differently, when we wish to change visibility, we actually have to make changes to each place the member was used.
  • Cannot access private members in methods that are added to the object at a later point.
  • Inability to create automated unit tests for private members.
  • Additional complexity when bugs require hotfixes.

Constructor Pattern

In object oriented languages, constructor is a special method used for initializing an object once it is created and allocated memory for that. In JavaScript, as almost everything is an object, we're most often interested in object constructors.

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

Object Creation

Three common ways to create JavaScript objects are:
  1. var newObject = {};
  2. var newObject = Object.create(null);
  3. var newObject = new Object();
Where the "Object" constructor in the final example creates an object wrapper for a specific value, or where no value is passed, it will create an empty object and return it.var newObject = new Object();

JavaScript (implementation of) Design Patterns

Here, we’ll explore the JavaScript implementation of some of the patterns.

Categories Of Design Pattern

Design patterns can be broken down into a number of different categories. Three of these categories are:
  1. Creational Design Patterns - focuses on handling object creation mechanisms. Examples are Constructor, Factory, Abstract, Prototype, Singleton and Builder.
  2. Structural Design Patterns - concerned with object composition and typically identify simple ways to realize relationships between different objects. Examples are Decorator, Facade, Flyweight, Adapter and Proxy.
  3. Behavioral Design Patterns - focuses on improving or streamlining the communication between disparate objects in a system. Examples are Iterator, Mediator, Observer and Visitor.

Anti-Patterns

While a pattern represents a best practice, an anti-pattern represents a lesson that has been learned. There are two notions of anti-patterns that are presented. Anti-Patterns:
  1. Describe a bad solution to a particular problem which resulted in a bad situation occurring
  2. Describe how to get out of said situation and how to go from there to a good solution
An anti-pattern could be a bad design that is worthy of documenting.

Writing Design Patterns

It would be good to consider these tips while designing new patterns:
  1. How practical is the pattern? - Patterns should provide proven solutions, not speculative ones.
  2. Keep best practices in mind - Design decisions should be based on the best practices.
  3. Our design patterns should be transparent to the user - Design patterns should be entirely transparent to any type of user-experience.
  4. Remember that originality is not key in pattern design - While writing design patterns, we do not need to be the original discoverer of the solutions. If the approach is strong enough to have broad useful applicability, it has a chance of being recognized as a valid pattern.
  5. Patterns need a strong set of examples - A patterns should have examples that demonstrates its successful application.

The Structure of a Design Pattern

A pattern is presented in the form of a rule that establishes the relationship between a context, a system of forces that arises in the context and a configuration that allows these forces to resolve themselves in the context.

Component Elements of a Design Pattern

A design pattern should have a:
  • Pattern name and a description
  • Context outline - the contexts in which the pattern is effective in responding to the users needs.
  • Problem statement - a statement of the problem being addressed.
  • Solution - a description of how the problem is solved.
  • Design - a description of pattern's design and the user's behavior in interacting with it.
  • Implementation - a guide to how the pattern is implemented
  • Illustrations - a visual representation of classes in the pattern
  • Examples - an implementation of the pattern in the minimal form.
  • Co-requisites - supporting patterns needed.
  • Relations - other patterns that resemble this pattern.
  • Known usage - where and how the pattern is used.
  • Discussions - thoughts on the benefits of the pattern.
Though the initial cost for creating a pattern is really high, the value return from that can be quite worth it.

What can be considered as a Pattern?

Not every algorithm, best practice or solution might not be considered as a complete pattern. Even if something appears to meet the criteria for a pattern, it cannot be considered as one until  it has gone through suitable testing by others for a period of time. A Pattern should be both a process and a thing.

Proto-patterns
: A pattern that has not yet been known to pass the "pattern"-ity tests.

Also, the individuals sharing the pattern may not have the time or interest of going through the "pattern"-ity process and might release a short description of their proto-pattern instead. Brief descriptions or snippets of this type of pattern are known as patlets.

The work involved in fully documenting a qualified pattern can be quite challenging. A pattern may be considered "good" if it does the following:
  1. Solves a particular problem: Patterns are not supposed to just capture principles or strategies. They need to capture solutions.
  2. The solution to this problem cannot be obvious: The best design patterns usually provide solutions to problems indirectly.
  3. The concept described must have been proven: If a pattern is highly speculative in nature, only the brave may attempt to use it.
  4. It must describe a relationship: The pattern must describe much deeper system structures and mechanisms that explain its relationship to code.

Advantages of Patterns

Why do we use Patterns? Here are some advantages:
  1. Patterns help in identifying minor issues that can cause serious issues during the software development process
  2. Patterns provide generalized solution, not specific to one problem
  3. Patterns help to make the code more DRY
  4. Patterns add to a developers vocabulary, which makes communication faster
  5. Patterns that are commonly used can be improved over time, making it more efficient
We use patterns every day. To understand how helpful patterns can be, lets review a simple element selection problem that jQuery solves for us.

Suppose we need to get the count of all the elements in the DOM with class 'foo', we can use a number of methods:
  1. Select all of the elements in the page and then store references to them. Next, filter this collection and use regular expressions (or another means) to only store those with the class "foo".
  2. Use a modern native browser feature such as querySelectorAll()
  3. Use native features such as getElementsByClassName()
But in jQuery, we can simply use $("selector"). This is significantly more easy to use for selecting HTML elements on a page versus having to manually handle opt for. This provides the most optimized way for accessing all the elements having a particular class or characteristics.

JavaScript Design Patterns - Introduction

What is a Design Pattern?

A pattern is a reusable solution or a template that can be applied to commonly occurring problems in software design.

Why patterns are important?

Design patterns have three main benefits:
  1.     Patterns are proven solutions
  2.     Patterns can be easily reused
  3.     Patterns can be expressive
Patterns provide a solution scheme, not exact solution for the problem. Patterns don’t solve all design problems nor do they replace good software designers, however, they do support them.

Learning JavaScript Design Patterns

This series is a summary of the book Learning JavaScript Design Patterns, by Addy Osmani, which I am currently reading. It is available for purchase via O'Reilly Media, but also available as a free eBook online. I'm looking forward to your feedback...