Successfully reported this slideshow.

Javascript design patterns


Published on

discussing most important design patterns like, module,reveal,prototype

Published in: Technology
  • Be the first to comment

Javascript design patterns

  1. 1. JavaScript Design PatternsJavaScript developers have several options for creating anObject in JavaScript, from the Object() method to Objectliterals to constructor functions, there are a lot of ways to getthe job done. This article will present a few choice Objectcreation Patterns. Pros and cons of each pattern are alsolisted.Curated by : Gomes, Jijo
  2. 2. Why should we follow a specific designpattern?- It helps to create modular and functional code- Unit testable/reusable code since entire programmingparadigm shift to client side
  3. 3. What is wrong here?This is a javascript file with a bunch offunctions written. There is no properstructure followed. There is a globalvariable resultCtrl, which means it isnot only accessible from the script filebut anywhere from the code. Sinceglobal variable can be accessed fromanywhere in the code, it is verydifficult to understand what changeswhat and when? This code is:-1. Difficult to understand.2. Difficult to maintain.3. Not re-usable.So how can we make it morestructured? Lets see how can we re-write this code using different designpatterns.
  4. 4. 1. Prototype PatternThe Prototype Pattern can be broken out into two mainsections including a constructor section and a prototypesection. Prototyping allows functions and properties to beassociated with objects. However, instead of each objectinstance getting a copy of all functions/properties each timean object is created, only one set of functions/propertiesexists across all objects resulting in less memoryconsumption. In other words, functions and properties aredefined once per prototype rather than once per object.Lets see how it works.
  5. 5. How does it work?One imporatant point in structuring aJavaScript code is that use namespacein your code . In this example, it uses anamespace called myNameSpace (if itis already defined it uses it otherwise itcreates a new). As you can see it has aconstuctor section where the member isintitialized and prototype section wherethe public methods are defined. Then itcreates a new instance of the Calculatorand uses the functions defined in it. Youcan create N number of Calculatorobjects through out your code. Asmentioned earlier it wont createduplicate of functions with each of theobjects created, instead all objectsshare the same method definitions likein C# or other programming languagesso it uses less memory. This pattern isused mainly to create JavaScriptlibraries. End user can use the existingfunctionalities or add new functionalitiesor modify existing ones throughprototypes.
  6. 6. Old code New CodeWhat changed?
  7. 7. 2. Module PatternIn JavaScript programing language, functions can be used as a Module. Sometimes, it is required to create asingleton object instead of creating instance of a class. Inside the module, the inner functions do have the staticscope with the other defined variables and functions.Maximum applications written in JavaScript languages are singletons only. Hence, they all are written in Modulepattern.A Module can be considered as a Singleton Class in C#. In a Module, all the variables defined are visible only inthe module. Methods in a module have scope and access to the shared private data and private methods. Hence,these methods are also called as Privileged methods.Therefore, by creating one anonymous function returns a set of privileged methods in a simple object literal format.And because of the closure principle, those privileged methods have access to the inner methods and variables ofthe anonymous function. We call it as a Module Pattern.Privileged MethodIn Module Pattern, you can write your private methods, private variables those you don’t want to expose to theother world and at the same time you will be able to write public and privileged methods also. The great usefulnessof this pattern is that you can very well access your private methods and variables from your methods those arecalled as Privileged Methods.ClosureIn order to learn Module Pattern, one must be aware of Closure principle. By using closure only modular patternbecomes very useful and powerful. Closure principle says that any inner function inside a parent function hasscope to the other inner function and variables although after the parent function has returned. In Module Pattern,Privileged methods have scope to the other private variables and methods of the module.
  8. 8. How does it work?As you can see, there is no separateconstructor section and method definitionsection like we have seen in Prototypepattern.Like mentioned previously, calculator objectis initialized through self execution of themethod body. That is, an anonymousfunction is executed with eq as parameter,and the result of the function (in this case,object literal after the return statement) isstored in the calculator object.Very important thing to note about ModulePattern is that, Normally each time a newobject is created a new set of functions willbe created. In this case 5 objects will create5 x 4 = 20 method definitions!. So its notfriendly on memory usage. So, that is thereason this pattern has a self executingmethod definition like given in the examplewhich in turn implements the Singletonconcept.
  9. 9. What changed?Old Code New Code
  10. 10. 3. Revealing Module PatternModule Pattern and Revealing Module Pattern are conceptually same,but differs in the way member functions are defined.
  11. 11. How does it work?As you can see, how methods are defineddiffers from Module Pattern. Methoddefinitions are given names through var andthe these variables are used in the returnstatement rather than function definitions likewe have seen in Module Pattern. Oneadvantage of using Revealing ModulePattern over Module Pattern is that we canhave private methods. In this example addmethod can be removed from the objectliteral in the return statement so that theobject will expose only subtract, multiply anddivide methods. But these 3 methods canaccess add method.
  12. 12. What changed?Old Code New Code
  13. 13. 4. Revealing Prototype PatternRevealing Prototype Pattern is a combination of Prototype Pattern andRevealing Module Pattern.
  14. 14. How does it work?
  15. 15. What are the other benefits?We have done the POC for patientfinancial.js and it workslike charm.Let’s all follow this pattern for better eco system.What next?Code will be unit testable(framework like jasmine etc can beadoptable)Code will be reusableClean html and js separation of concern
  16. 16. Reference:Book – “JavaScript: The Good Parts” – Douglas Crockford that follow the patterns are a lot, few are here.knockoutJSAngularJSBackbone.JSEmber.JSMany in github…