Upgrade to Pro — share decks privately, control downloads, hide ads and more …

An Overview of Javascript Design Patterns

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

An Overview of Javascript Design Patterns

A look into some common Javascript patterns in use today with a few examples.

Avatar for Chris Nyaga

Chris Nyaga

January 19, 2019

More Decks by Chris Nyaga

Other Decks in Programming

Transcript

  1. Understanding the basics • What are the main characteristics of

    JavaScript? ◦ JavaScript is asynchronous, supports first-class functions, and is prototype-based. • What are design patterns, and how do they support software architects? ◦ Design patterns are reusable solutions to commonly occurring problems in software design. They are proven solutions, easily reusable and expressive. They lower the size of your codebase, prevent future refactoring, and make your code easier to understand by other developers. • What is JavaScript and how did it come to life? ◦ JavaScript is a client-side scripting language for browsers first created by Brendan Eich for Netscape Navigator by what is now Mozilla.
  2. ...cont • What is ECMAScript? ◦ ECMAScript is a standardized

    scripting language specification which all modern browsers try to support. There are multiple implementations of ECMAScript, the most popular of which is JavaScript. • What is a proto-pattern? ◦ A proto-pattern is a pattern-to-be if it passes a certain period of testing by various developers and scenarios where the pattern proves to be useful and gives correct results. • What is an anti-pattern? ◦ If a design pattern represents good practice, then an anti-pattern represents bad practice. An example of an anti-pattern would be modifying the Object class prototype. Changes to the Object prototype can be seen in all of the objects that inherit from this prototype (that is, almost all objects in JavaScript).
  3. ...cont • How do we categorize design patterns? ◦ Design

    patterns can be creational, structural, behavioral, concurrency, or architectural. • What are a few examples of design patterns? ◦ Some examples discussed in the article above include the constructor pattern, the module pattern, the revealing module pattern, the singleton pattern, the observer pattern, the mediator pattern, the prototype pattern, the command pattern, and the facade pattern.
  4. Why use design patterns anyway? • They are proven solutions:

    Because design patterns are often used by many developers, you can be certain that they work. And not only that, you can be certain that they were revised multiple times and optimizations were probably implemented. • They are easily reusable: Design patterns document a reusable solution which can be modified to solve multiple particular problems, as they are not tied to a specific problem. • They are expressive: Design patterns can explain a large solution quite elegantly. • They ease communication: When developers are familiar with design patterns, they can more easily communicate with one another about potential solutions to a given problem. • They prevent the need for refactoring code: If an application is written with design patterns in mind, it is often the case that you won’t need to refactor the code later on because applying the correct design pattern to a given problem is already an optimal solution. • They lower the size of the codebase: Because design patterns are usually elegant and optimal solutions, they usually require less code than other solutions.
  5. A few Javascript Properties JavaScript Supports First-class Functions JavaScript treats

    functions as first-class citizens, meaning you can pass functions as parameters to other functions just like you would any other variable. // we send in the function as an argument to be // executed from inside the calling function function performOperation(a, b, cb) { var c = a + b; cb(c); } performOperation(2, 3, function(result) { // prints out 5 console.log("The result of the operation is " + result); })
  6. ...cont JavaScript Is Prototype-based As is the case with many

    other object-oriented languages, JavaScript supports objects, and one of the first terms that comes to mind when thinking about objects is classes and inheritance. This is where it gets a little tricky, as the language doesn’t support classes in its plain language form but rather uses something called prototype-based or instance-based inheritance. JavaScript Event Loops If you have experience working with JavaScript, you are surely familiar with the term callback function. For those not familiar with the term, a callback function is a function sent as a parameter (remember, JavaScript treats functions as first-class citizens) to another function and gets executed after an event fires. This is usually used for subscribing to events such as a mouse click or a keyboard button press.
  7. Into design patterns now • You’ve likely found yourself writing

    code that looks similar to the solution of an entirely different problem you’ve handled before. • You may not know it, but you’ve used a JavaScript design pattern. • Design patterns are reusable solutions to commonly occurring problems in software design • Proto-patterns ◦ A proto-pattern is a pattern-to-be if it passes a certain period of testing by various developers and scenarios where the pattern proves to be useful and gives correct results. • Anti-patterns ◦ Anti-pattern represents bad practice.
  8. .cont Design Pattern Categorization Design patterns can be categorized in

    multiple ways, but the most popular one is the following: • Creational design patterns • Structural design patterns • Behavioral design patterns • Concurrency design patterns • Architectural design patterns
  9. .cont Creational Design Patterns These patterns deal with object creation

    mechanisms which optimize object creation compared to a basic approach. The basic form of object creation could result in design problems or in added complexity to the design. Creational design patterns solve this problem by somehow controlling object creation. Some of the popular design patterns in this category are: • Factory method • Abstract factory • Builder • Prototype • Singleton
  10. .cont Structural Design Patterns These patterns deal with object relationships.

    They ensure that if one part of a system changes, the entire system doesn’t need to change along with it. The most popular patterns in this category are: • Adapter • Bridge • Composite • Decorator • Facade • Flyweight • Proxy
  11. .cont Behavioral Design Patterns These types of patterns recognize, implement,

    and improve communication between disparate objects in a system. They help ensure that disparate parts of a system have synchronized information. Popular examples of these patterns are: • Chain of responsibility • Command • Iterator • Mediator • Memento • Observer • State • Strategy • Visitor
  12. .cont Concurrency Design Patterns These types of design patterns deal

    with multi-threaded programming paradigms. Some of the popular ones are: • Active object • Nuclear reaction • Scheduler
  13. .cont Architectural Design Patterns Design patterns which are used for

    architectural purposes. Some of the most famous ones are: • MVC (Model-View-Controller) • MVP (Model-View-Presenter) • MVVM (Model-View-ViewModel)
  14. .cont Design Pattern Examples Each of the design patterns represents

    a specific type of solution to a specific type of problem. There is no universal set of patterns that is always the best fit. We need to learn when a particular pattern will prove useful and whether it will provide actual value.
  15. .cont Constructor Pattern When thinking about classical object-oriented languages, a

    constructor is a special function in a class which initializes an object with some set of default and/or sent-in values. Common ways to create objects in JavaScript are the three following ways: // either of the following ways can be used to create a new object var instance = {}; // or var instance = Object.create(Object.prototype); // or var instance = new Object();
  16. .cont After creating an object, there are four ways (since

    ES3) to add properties to these objects. They are the following: // supported since ES3 // the dot notation instance.key = "A key's value"; // the square brackets notation instance["key"] = "A key's value"; // supported since ES5 // setting a single property using Object.defineProperty Object.defineProperty(instance, "key", { value: "A key's value", writable: true, enumerable: true, configurable: true });
  17. .cont // setting multiple properties using Object.defineProperties Object.defineProperties(instance, { "firstKey":

    { value: "First key's value", writable: true }, "secondKey": { value: "Second key's value", writable: false } }); The most popular way to create objects is the curly brackets and, for adding properties, the dot notation or square brackets.
  18. .cont Prototype Pattern It enables us to create objects which

    can serve as a prototype for other objects being created. The prototype object is used as a blueprint for each object the constructor creates.
  19. .cont var personPrototype = { sayHi: function() { console.log("Hello, my

    name is " + this.name + ", and I am " + this.age); }, sayBye: function() { console.log("Bye Bye!"); } }; function Person(name, age) { name = name || "John Doe"; age = age || 26; function constructorFunction(name, age) { this.name = name; this.age = age; }; constructorFunction.prototype = personPrototype; var instance = new constructorFunction(name, age); return instance; }
  20. .cont var person1 = Person(); var person2 = Person("Bob", 38);

    // prints out Hello, my name is John Doe, and I am 26 person1.sayHi(); // prints out Hello, my name is Bob, and I am 38 person2.sayHi();