MODERN JAVASCRIPT APPLICATIONS Volodymyr VoityshynRivne 2013
How to get well structured JavaScript code? How to get well structured JavaScript code?
Client JavaScript Evolution 1. Client JavaScript resolved auxiliary tasks 2. Single Page Web Applications 3. Real time applications 4
Contents I. Some Useful Constructions II. What is wrong? III. JavaScript & OOP IV. Module Pattern V. Object Oriented Design Patterns VI. MV* Patterns via BackboneJS VII. Dependencies Management 5
I. Some Useful Constructions
Closures 7
IIFE 8
Named Parameters Must be documented 9 It’s useful for 4 and more parameters
II. What is wrong?
Global Functions  Avoid global functions  Use instead:  Classes  Modules 11
Mixing JavaScript with HTML ▪ Place HTML and JavaScript in separated files ▪ Assign event handlers with JavaScript 12
Mixing JS & Server Code is Bad ASP.NET MVC Razor 13
Mixing JS & Server Code is Acceptable ASP.NET MVC Razor 14
III. JavaScript & OOP
Fact #1 Everything is an object 16
… even primitives and functions 17
Creating an Object 18
Fact # 2 Object members can be added/deleted dynamically 19
Defining Members 20
Creating an Object with JSON Notation 21
Deleting Members 22
Fact #3 All object members are public 23
Fact #4 Objects are hash tables 24
Access to a Property with [] 25
Fact #5 Inheritance is based on prototypes 26
Inheritance Object vehicle + name + run() bicycle + wheels Sample_2_01 27
Fact #6 Functions can be considered as classes 28
Pseudo Class Object Vehicle + name + run() 29
The “prototype” Property Object Vehicle + name + run() 30
Pseudo Class Inheritance Object Vehicle + name + run() Bicycle + wheels Sample_2_02 31
Inheritance: Practice Hints  Avoid a too long prototype chain  Avoid extending prototypes of built-in objects  Use framework functions for extending objects:  $.extend()  _.extend()  _.mixin() 32
Virtual Functions 33
Static Members 34
IV. Module Pattern
Module Pattern Intent Provides both private and public encapsulation for classes
Module Example ▪ Closure is used for private state ▪ “Public” object is returned ▪ Created by IIFE Sample_3_01_Module_Counter 37
Import Dependencies 38
Extending Sample_3_02_Module_Strings 39
Extending jQuery Module 40
Extending Underscore Module 41
Page Code Behind as Module Page (HTML + CSS) Code Behind (JavaScript Module) Handle Events Read Data Put Data 42 Sample_3_04_PageCodeBehind_Module
Advantages vs. Disadvantages  Advantages  Simple in development  Possibility of using a page base class  Disadvantages  Becomes too large in case of a complex page  Hard in automated testing  Can’t be used with SPA 43
Class as Module 44
V. Object Oriented Design Patterns
V.1. Creational Patterns “… help make a system independent of how its objects are created, composed, and represented” (GoF)
Factory Pattern Intent Provides an interface for creating families of related or dependent objects without specifying their concrete classes. (GoF)
Classical Abstract Factory AbstractComponentFactory - components + create(string) ChComponentFactory IEComponentFactory Calendar + render() IECalendar + render() ChCalendar + render() Grid + render() IEGrid + render() ChGrid + render() Sample_4_01_AbstractFactory_CrossBrowser_Component
Service Locator & IoC  Provides abstract interface for instantiating objects  Resolves dependencies among objects  Manages objects’ life cycle
Prototype Pattern Intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. (GoF) Prototype New Object clone()
Prototype by Native JavaScript Object p id, name p1 p2
Prototype as a Shallow Copy Object p3 id, name p4 id, name p5 id, name
Prototype as a Deep Copy Object p6 id, name p7 id, name
Classical Prototype
Cloning DOM Elements
V.2. Structural Patterns “… are concerned with how classes and objects are composed to form larger structures” (GoF)
Adapter Pattern Intent Convert the interface of a class into another interface clients expect (GoF) Client Expected Interface Old Interface
Adapting to Underscore Interface
Decorator Pattern Intent Attach additional responsibilities to an object dynamically (GoF) Decorator 2 Decorator 1 an ObjectClient
Classical Decorator
Decorator and IIFE
Decorator with Closure
Façade Pattern Intent Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. (GoF) A Complex System Façade Client
Façade in jQuery XMLHttpRequest $.ajax() Client document.createElement() $(“<tag>”) Client
Façade: Important Consideration Performance Comfortable Interface
V.3. Behavioral Patterns “… are concerned with algorithms and the assignment of responsibilities among objects” (GoF)
Observer Pattern Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. (GoF) Subject Observer 1 Observer 2 Observer 3 Notify about changes Notify about changes
Publish/Subscribe
Publish/Subscribe & Backbone Event
Mediator Pattern Intent Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. (GoF)
Mediator as Event Buss Event Buss Module 1 Module 2 Publishes an event Listens an event http://thejacklawson.com/Mediator.js/ Transfers an event from the publisher to the listeners
Mediator as Web Modules Manager Web Module 1 Web Module 2 Web Modules Manager Nicholas Zakas: Scalable JavaScript Application Architecture  Manages a web module life cycle  Manages collaboration among modules Web Module Context  Everything a web module knows about the application  Manage user’s interaction  Don’t know about each other Web Module ↓ an independent part of GUI
Strategy Pattern Intent Define a family of algorithms, encapsulate each one, and make them interchangeable. (GoF)
Sorting Algorithms as Strategy
VI. MV* Patterns via BackboneJS
Model – View – Controller View Model Controller Main goal - separate view and data
Top JavaScript MVC Frameworks Knockout.js Ember.js Angular.js Backbone.js
Backbone Object Types 78  Events  Model  Collection  View  Router
Backbone.js Typical Stack Backbone.js Underscore.js jQuery Require.js
Backbone Advantages 80  Simple in usage  Defines major types of an application objects  Gets much freedom for application structure  Easily extensible  Gets on well with other frameworks
VII. Dependencies Management
What is a bad design?  Inflexibility  Fragility  Solidity
Coupling A measure of how much a module relies on other modules
Cohesion A measure of how closely related the members of a module are to the other members of the same module HighLow
What is a good design?  Flexible  Robust  Reusable
What’s a main problem?
What is a key to success? Manage dependencies!
Dependency Inversion Principle A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions. (Robert C. Martin) The Dependency Inversion Principle (by Robert C. Martin)
Dependency Inversion Formula X Y X Y IY
Design Quality Criteria  How easily could your code be covered by unit tests?  Could web modules be used independently?
Class Dependencies  Passive Injection  Constructor  Method  Field  Active Injection  Service Locator
Module Dependencies  Asynchronous Module Definition (AMD) https://github.com/amdjs/amdjs-api/wiki/AMD define(id?, dependencies?, factory)
RequireJS Module Sample 93
Web Modules Dependencies (1)
Web Modules Dependencies (2) 95 Models & Collections Root View View 1 View 2 View 1 View 1 View 1 View 1
For further reading… 1. JavaScript Good Parts 2. JavaScript Garden 3. Leaning JavaScript Design Patterns (by Addy Osmani) 4. JavaScript Module Pattern: In-Depth (by Ben Cherry) 5. Scalable JavaScript Application Architecture (by Nicholas Zakas) 6. Journey Through The JavaScript MVC Jungle (by Addy Osmani) 7. Developing Backbone.js Applications (by Addy Osmani) 8. superhero.js

Modern JavaScript Applications: Design Patterns