Friday, April 16, 2010

JavaScript Design Patterns - Encapsulation & Information Hiding

Despite the fact that JavaScript is an object-oriented language, it does not have any built-in mechanisms for declaring members to be public or private.

There are several established patterns for creating objects with public, private, and privileged methods, each with its own strengths and weaknesses.

Encapsulation and Information Hiding

How is encapsulation related to information hiding? You can think of it as two ways of referring to the same idea.

Information hiding is the goal, and encapsulation is the technique you use to accomplish that goal.

Encapsulation can be defined as the hiding of internal data representation and implementation details in an object. The only way to access the data within an encapsulated object is to use defined operations.

In OO Languages they use "private" keyword.
In JavaScript, we will use the concept of the closure to create methods and attributes that can be only accessed from within the object. It is more complicated (and confusing) than just using keywords, but the same end result can be achieved.

The role/importance of the Interface:

Interface provides a contract that documents the publicly accessible methods. It defines the relationship that two objects can have; either objects in this relationship can be replaced as long as the interface is maintained.

The ideal software system will define interfaces for all classes. Those classes will provide only the methods defined in their interfaces; any other method will be kept private. All attributes will be private and only accessible through accessor and mutator operations defined in the interface.

This 'interface' explanation you can find in many object oriented languages books (java, C#, ActionScript 3.0, Objective-C 2.0, etc, etc.).


Basic Patterns:

- fully exposed object is the simplest but provides only public members.
Fully Exposed Demo
- using 'underscores' to denote methods and attributes that are intended to be private.
Underscores Demo
- third, uses 'closures' to create true private members, which can only be accessed through the use of privileged methods.
Using Closures to create private memebers Demo

No comments:

Post a Comment