37

With Javascript appearing to be the ubiquitous programming language of the web over the next few years, new frameworks popping up every five minutes and event driven programming taking a lead both server and client side:

Do you as a Javascript developer consider the traditional Design Patterns as important or less important than they have been with other languages / environments?.

Please name the top three design patterns you, as a Javascript developer use regularly and give an example of how they have helped in your Javascript development.

Lewis
  • 483
  • 4
  • 7
  • 5
    Some people argue that design patterns (especially the GoF ones) are signs of language deficiency (see [this discussion](http://c2.com/cgi/wiki?AreDesignPatternsMissingLanguageFeatures)). Since JavaScript is prototypal and functional in nature, I would say that another set of patterns is applicable/useful. –  May 06 '11 at 10:21
  • very interested in the responses ... +1 for question :) – usoban May 06 '11 at 10:25
  • 2
    The book *JavaScript Patterns* by Stoyan Stefanov is a great resource on tons of patterns you can use in JS. Many of them exist specifically for JS, and not for any other language. – IgorGanapolsky Jul 21 '11 at 21:22
  • Javascript has its own patterns. In addition to the book mentioned by Igor, there's also Addy Osmani's [Learning Javascript Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/), which is free. – user16764 Sep 21 '12 at 21:20
  • Possible duplicate of [Are there any OO-principles that are practically applicable for Javascript?](https://softwareengineering.stackexchange.com/questions/180585/are-there-any-oo-principles-that-are-practically-applicable-for-javascript) – gnat Jul 04 '17 at 08:09

4 Answers4

23

Do you as a Javascript developer consider the traditional Design Patterns as important or less important than they have been with other languages / environments?.

Classical design patterns do not apply to JavaScript.

What does apply is writing modular and functional code.

You should use a mixture of Constructors and first class functions.

As a JavaScript developer I personally push towards treating JavaScript as LISP rather then Java. So try to emulate monads and high level functional style code rather then trying to emulate classical OOP code.

Please name the top three design patterns you, as a Javascript developer use regularly and give an example of how they have helped in your Javascript development.

Again design patterns do not really apply that much but below are three important constructs.

  1. Use of closures
  2. Use of first class functions
  3. Use of Object factories with or without new

Please leave some kind of context for which I can show examples of these kind of techniques compared to doing the same kind of code using traditional design patterns.

Let's take a look at some of the classical Design Patterns and how to implement them in js as well as alternative patterns more suited to js itself:

Observer Pattern:

In node.js this is simply events.EventEmitter. In jQuery this is $.fn.bind && $.fn.trigger. In backbone this is Backbone.Events.trigger and Backbone.Events.bind. This is a very common pattern used in day to day code.

I never stop and think "Hey I'm using an observer pattern here!". No this is just a low level way to pass messages around or a way to cascade change.

For example in backbone all the MVC views bind to the models onchange event so changing the model cascades any changes automatically to the view. Yes this is a powerful pattern, but it's use is so common in event driven programming that were not realising were using it everywhere.

In the WebSocket prototcol we have .on which we use to bind to on("message", ... events. Again this is very common but it's an observer on a stream rather then your classical OOP based while (byte b = Stream.ReadNextByte()).

These are all powerful uses of the Observer pattern. But this isn't a pattern you use. This is a simple part of the language. This is just code.

Memento Pattern:

This is simply JSON. It allows you to serialize the state of an object so you can undo an action.

function SomeObject() {
    var internalState;

    this.toJSON = function() {
        return internalState;
    }

    this.set = function(data) {
        internalState = data;
    }

    this.restore = function(json) {
        internalState = JSON.parse(json);
    }
}

var o = new SomeObject();
o.set("foo"); // foo
var memento = JSON.stringify(o);
o.set("bar"); // bar
o.restore(memento);

In JavaScript we natively support an API for mementos. Just define a method called toJSON on any object. When you call JSON.stringify it will internally call .toJSON on your object to get the real data you want to serialize to JSON.

This allows you to trivially make snapshots of your code.

Again I don't realise this a memento pattern. This is simply using the serialization tool that is JSON.

State Pattern / Strategy Pattern:

You don't need a state pattern. You have first class functions and dynamic types. Just inject functions or change properties on the fly.

Raynos
  • 8,562
  • 33
  • 47
  • Raynos, Nice answer. As for examples, I was thinking more from conceptual level. For example: "an observer pattern helped out in the situation ..." –  May 06 '11 at 13:00
  • @Lewis pick a few design patterns you like and I'll try to suggest more appropriate functional alternatives later. – Raynos May 06 '11 at 13:03
  • The effort approach and answer are brilliant Raynos. Thanks. – Lewis May 07 '11 at 15:41
  • @Lewis I tried to look at a couple more but got stumped since they are all tailored for strict classical OO languages. if there are other specific design patterns you want me to look at let me know. – Raynos May 07 '11 at 15:53
  • You forgot about **Prototype** pattern - aka _stupid javascript does not even have normal oop_ ;) – c69 Oct 26 '11 at 17:10
9

Take this answer as subjective opinion.

Do you as a Javascript developer consider the traditional Design Patterns as important or less important than they have been with other languages / environments?

If you mean traditional design patterns like Gang of Four, then most of the techniques are language/platform agnostic like "Program to an interface, not an implementation" or "Favor object composition over class inheritance" and are equally important also to JavaScript developers.

More specific patterns like creational, structural and behavioral may or need not to be used in the same way or as frequently as in other languages because language features can affect their use to great extent. Some languages (JavaScript included) therefore have their own design patterns based on functionality or syntactic sugar they offer.

In general I would say that traditional design patterns are as important as they are in other languages, but JavaScript specific patterns are more important than traditional ones.

name the top three design patterns you, as a Javascript developer use regularly and give an example of how they have helped in your Javascript development

Among the Essential JavaScript Design Patterns I mostly use these:

1. Constructor pattern (With Prototypes)

Especially on the server side when writing node.js stuff, because it's well suited for writing modules although it lacks native encapsulation. Also it's popular for many other developers if you browse repositories on GitHub, so familiarity with this pattern can help you better understand other codes.

2. Revealing Module Pattern

Offers modularity with encapsulation.

3. DRY Pattern

This is rather scenario specific, although every developer should use it as much as (im)possible.

yojimbo87
  • 556
  • 1
  • 5
  • 15
  • Thanks! Nice answer, and the kind of response I was hoping for. Although the question can be viewed as subjective, a good response like this suggests that there is an appropriate answer. Will wait for more responses before 'signing off'. –  May 06 '11 at 12:57
2

Design patterns are taught in design classes for CS. They aren't essential, but really helpful if you can find analogous situations to have a solution that has been thought through.

It also allows programmers to communicate more easily. You can talk to your coworker in terms of the patterns as well. If you say here I have my Observer, then it is pretty well understood what is kind of going on.

People will naturally come up with solutions that will fit into a design pattern on their own, but the design patterns help to define terminology and standard ideas that can be helpful.

There's nothing super remarkable about the patterns, the nicest thing is that they are ideas that are canonized and defined in ways that are repeatedly useful.

1

Do you as a Javascript developer consider the traditional Design Patterns as important or less important

They are vital.

This is because concepts for reusable solutions can transcend language. - syntax changes - implementation changes - Notion for pattern still exists.

Developers from any language can learn advanced JS by learning patterns, not syntax. Those who do not know this are missing out.

Please name the top three design patterns you, as a Javascript developer use regularly

There are patterns that are used frequently which some would "argue" against. However, they are good to know because they are extremely common and powerful in advanced JS.

1- Namespace - wrap your code in an object.

var x = (function(){})();

2- ObjectConfiguration, Factory-like pattern. -Pass an object to a function, not a bunch of vars.

var product = factory({});

3- Callback function. - Pass a function as a parameter, to be called when task is complete.

function longTask(function(){//call me when done});

Like I said, some may argue that these are not patterns, but they are very common and very powerful, and should be mentioned because they are indeed very useful reusable solutons to common problems. Which is the definition of Design Pattern.

Excellent question.

Hope that helps.

Jack Stone
  • 1,151
  • 10
  • 11