Posts

Showing posts with the label OOP

JavaScript Adapter Design Pattern

Image
Today we'll continue the JavaScript Design Patterns series by discussing the Adapter Pattern . Adapters are added to existing code to reconcile two different interfaces. They allows programming components to work together that otherwise wouldn't because of mismatched interfaces. Adapter may be also used to ease the use with the existing interface. If the existing code already has an interface that is doing a good job, there may be no need for an adapter. But if an interface is unintuitive or impractical for the task at hand, you can use an adapter to provide a cleaner or more option-rich interface. Let's see how it looks in the following illustration: Here we depict the example of legacy  IDataManager interface, which is deeply used within the system. With the introduction of Redis database into the system, we need an adapter to fill the gaps. Our Adapter class has to implement the getData method, to make it consistent with the system, calling in turn the scan ...

JavaScript Promise

Nothing weights lighter than a promise This maybe true regarding to human promises, however in the programming domain, promises are always kept. Following this optimistic note, today we'll be talking about JavaScript promises. Event Handling Problem Let's see what promises are good for and their basic capabilities starting with a problem they come to solve. Events are great for things of a repetitive nature like keydown , mousemove etc. With those events you don't really care about what have happened before you attached the listener. On contrary calling services and processing their response is a completely different kind of beast. Have a look at the following function, which reads a json file and returns it's content or an error in case of something goes wrong. function readJSON(filename, callback) { fs.readFile(filename, 'utf8', function (err, res) { if (err) { return callback(err); } try { res = JSON.parse(res); ...

JavaScript Singleton Design Pattern

Image
In the previous articles we discussed Factory , Builder  and Prototype design pattern . Today it's time to draw a line under creational design patterns by talking about Singleton Pattern . Even though it's the most well known design pattern among the developers, the thought of writing one in JavaScript, makes most developers tremble. Naturally there is no reason for that and in fact implementing it is not that big of a deal. But first, let's see how it looks in the following illustration: Basically our singleton contains one instance of itself and returns only it. Client cannot create a new instance or get other instance then one proposed by singleton. So how do we implement it? The same way, like in any other language - using static classes. To brush off the rust, please read Object Oriented JavaScript article. var Singleton = (function () { var instance; function createInstance() { var object = new Object(); return object; } ...

JavaScript Builder Design Pattern

Image
Today I would like to continue the series about design patterns we started with Factory Patterns in JavaScript and talk about the Builder pattern . For some reason it's being left behind in any design pattern usage in JavaScript. Maybe it was correct in the front end domain, but surely not in Node.js. Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. The Builder pattern is based on Directors and Builders . Any number of Builder classes can conform to an IBuilder interface, and they can be called by a director to produce a product according to specification. The builders supply parts that the Product objects accumulate until the director is finished with the job. I'll be using the example from the factory pattern article to emphasize the differences between the patterns. Consider the class diagram for the Builder pattern: And the implementation: funct...

JavaScript Factory Patterns

Image
Since June has 5 Sundays in it, today I will write a bonus article :) Following our last week's article about Publish and Subscribe Pattern with Postal.js , I'd like to broaden the topic talking about design patterns . The design patterns from the Gang of Four book offer solutions to common problems related to the object-oriented software design. It has been in use for decades and implemented in all server side languages. It's time we use them with JavaScript and start to write some piece of decent code. I'll be writing a series of articles covering all of them. As in the book, we'll be starting with creational patterns  and cover both Abstract Factory and Factory Method patterns. Abstract classes and interfaces enforce consistent interfaces in derived classes. In JavaScript we must ensure this consistency ourselves by making sure that each 'concrete' object has the same interface definition (i.e. properties and methods) as the others. Abstr...

Getters and Setters in JavaScript

This is the fourth article in the series of Object Oriented Javascript . Following our discussion on  inheritance  and it's integration with  modular design pattern , I'd like take a deeper look into encapsulation  and usage of mutator methods . Getters and setters allow you to build useful shortcuts for accessing and mutating data within an object. __defineGetter__ and __defineSetter__ If you had searched for the information over the internet, you would have probably encountered recommendations, mostly from Microsoft :), to use __defineGetter__ and __defineSetter__ . You may have also found some hacks for IE7 and even IE6. Even from a look at them you can smell something fishy. JavaScript is not C and doesn't encourage usage of underscores. Your gut feeling is right. This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages o...

Modular Design Patterns and Inheritance

Last week we talked about JavaScript inheritance  and if you recall we had talked about modular design patterns in JavaScript  just a month ago. I would also like to talk about how to connect both modules and class inheritance. We've already discussed that modules are classes. So if we can link classes by inheritance relationship, the logical half of our brain suggests that we should be able to link modules as well. The logic prevails - we can. AMD and inheritance I'll be using the classes we defined in the inheritance article, Mammal and Dog , and create modules from them. Let's start with our super class: (function () { 'use strict'; define(function() { function Mammal() { this.age = 0; console.info("Mammal was born"); } Mammal.prototype.grow = function() { this.age += 1; console.log("Mammal grows"); }; return Mammal; }); }()); Let's use it in our entry point JavaScript file. Just t...

Object Oriented JavaScript - Inheritance

Up until now, we've talked about Object Oriented JavaScript  programming. Creating classes though doesn't make you code truly object oriented. What you lack is polymorphism , which is achieved through inheritance. JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object. Prototype Chain When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. null, by definition, has no prototype, and acts as the final link in this prototype chain . Object.create After being long advocated for ,  EcmaScript 5  has standardized a new method called  Object.create . To keep up with progress, I...

Object Oriented JavaScript

The JavaScript language is simple and straightforward and often there’s no special syntax for features you may be used to in other languages, such as namespaces, modules, packages, private properties, and static members. For this reason, a lot of ambiguity lingers thought the streets of JavaScriptville. Namespaces Before we start creating classes, I would like to introduce the concept of namespaces. Namespaces help reduce the number of globals required by our programs and at the same time also help avoid naming collisions or excessive name prefixing. JavaScript doesn’t have namespaces built into the language syntax, but this is a feature that is quite easy to achieve. We'll create a global function, which will create a namespace according to the received fully qualified namespace name (e.g. JsDeepDive.Common.Managers). We'll iterate over each segment of the namespace and create namespaces where are needed. Full implementation looks like this: function namespace(names...