It is tempting to treat software design patterns as checklists to learn. There’s something so nice about the idea that if we just “memorize those 23 things,” we’ll be all set. The bad news is that, as mentioned in Chapter 2 , even learning the latest in JavaScript should keep you busy until the free and open web fails or the sun goes supernova.

Additionally, patterns have a mixed reputation. On the one hand, they can help to handle complexity. On the other hand, they can create complexity where it is not needed. Sometimes, extracting functions, extracting objects, breaking code up into modules, and depending on a framework (which itself likely exposes and documents patterns of its own) are simpler choices. Keeping the YAGNI (“Ya ain’t gonna need it”) principle in mind and considering the interface you want for your code are the best guidelines when deciding when to implement (or remove) a design pattern.

The good news is that these patterns aren’t that hard to learn and are easy to reference so you don’t have to memorize every detail.  Additionally, we’ll focus on just seven of them here, chosen by their likelihood to solve real problems in legacy code. Just learn these seven patterns, and it will change your life! 1 Here they are:

  • Template method
  • Strategy
  • State
  • null object
  • Decorator (“Wrapper” section)
  • Adapter (“Wrapper” section)
  • Facade

As we’re describing fairly high-level changes for most of these patterns, it’s likely that the specific interfaces will change. And we should be aware that when changing an interface, we might not be “refactoring.” Sometimes, patterns are presented with mechanics to provide a safe path between code before and after a pattern is applied. In lieu of those, the practical steps for applying every pattern presented are:

  1. Save and check the code into version control.
  2. Make a small change.
  3. Repeat steps 1 and 2 until you’re done.

Follow that process, and write tests as you see fit. We’ve already explored a few ways to do that, including test-driven development (TDD), characterization tests, end-to-end tests, and unit tests.

We are striving for code we can be confident in. That means in addition to code being well tested, it should also provide sensible interfaces. That is the priority in this chapter .

Template Method

The template method pattern is useful for when you have two algorithms that serve the same purpose, with minor variations. The basic mechanics require moving some part of two subclass functions into the parent class.

Although the refactoring itself is fairly simple, in this section we’ll talk about how you might get to the point of wanting to do it, as well as what you might do instead.

Let’s say you have a Person class. As the saying goes, there are 10 types of people: those who understand binary numbers, and those who don’t. To start out, our Person manages this knowledge in a boolean type variable:

class Person{
  constructor(binaryKnower){
    this.binaryKnower = binaryKnower;
  };
  whatIs(number){ return number };
  whatIsInBinary(number){ return Number('0b' + number) };
};

const personOne = new Person(true);
const personTwo = new Person(false);

[personOne, personTwo].forEach(person => {
  if(person.binaryKnower){
    console.log(person.whatIsInBinary(10));
  } else{
    console.log(person.whatIs(10));
  }
});

Our personOne knows binary, so we’ll get 2 (which is one, zero in binary in case you missed the joke) logged first. Our personTwo just assumes that one, zero is 10 , so that’s logged second.

This works fine, but it leaves our interrogation of binary knowledge up to our client code (e.g., our interface, tests, or whatever code might use this as a module). Consequently, we’re stuck with an if statement any time we want to get all of our people to interpret a number. Generally speaking, we want to eliminate conditionals where it is sensible and also push complexity away from the API (which you might think of as “the public interface,” “the inputs and outputs for the tests,” or “the way we use the code”). It’s generally better if we can let the deeper parts of the code handle complexity.

Let’s move that conditional into the Person object, and while we’re at it, let’s use a string for binary knowledge instead of a boolean:

class Person{
  constructor(typeOfPerson){
    this.typeOfPerson = typeOfPerson;
  }
  whatIs(number){
    return number;
  };
  whatIsInBinary(number){
    return Number('0b' + number);
  };
  log(number){
    if(this.typeOfPerson === "binary knower"){
      console.log(this.whatIsInBinary(10));
    } else{
      console.log(this.whatIs(10));
    }
  };
};

const personOne = new Person("binary knower");
const personTwo = new Person("binary oblivious");

[personOne, personTwo].forEach(person => {person.log(10)});

Now our conditional is neatly tucked away in the log function of the Person object. Next, instead of just having a type variable to let the logging function know what to do, let’s use subclasses and get rid of the conditional altogether:

class Person{}

class BinaryKnower extends Person{
  log(number){
    console.log(this.whatIsInBinary(number));
  };
  whatIsInBinary(number){
    return Number('0b' + number);
  };
};

class BinaryOblivious extends Person{
  log(number){
    console.log(this.whatIs(number));
  };
  whatIs(number){
    return number;
  }
};
const personOne = new BinaryKnower();
const personTwo = new BinaryOblivious();
[personOne, personTwo].forEach(person => person.log(10));

Now our log function is looking a little repetitive. Let’s bring it into the Person object:

class Person{
  log(number){
    console.log(this.whatIs(number));
  };
};

class BinaryKnower extends Person{
  whatIs(number){ return Number('0b' + number) };
};

class BinaryOblivious extends Person{
  whatIs(number){ return number };
};
const personOne = new BinaryKnower();
const personTwo = new BinaryOblivious();
[personOne, personTwo].forEach(person => person.log(10));

Notice that we had to give our functions ( whatIs and whatIsInBinary ) the same name to make that change.

When did we apply the template method pattern?

In case it’s unclear, it was in this last step of moving the log function from the subclasses into Person . The template method is really simple, so you might accidentally stumble into doing it just by moving functions around between objects. It is a specialized form of what is sometimes called the “pull-up method” of refactoring, where  functions (or methods, depending on the context) are brought into the superclass. What makes it the template method pattern is that some of the implementation (in this case, the whatIs function) creates variation from the subclasses.

A Functional Variant

For a function as basic as ours, you might wonder if it justifies the superclass. We could also have done this:

function log(person, number){ 
  console.log(person.whatIs(number));
};
class BinaryKnower{ whatIs(number){ return Number('0b' + number) } };
class BinaryOblivious{ whatIs(number){ return number } };
const personOne = new BinaryKnower();
const personTwo = new BinaryOblivious();
[personOne, personTwo].forEach(person => { log(person, 10) });

Now we’re passing two explicit arguments to the function, and must explicitly reference the person object rather than this . In the previous code snippet, we had one implicit parameter and one explicit one. You might prefer either approach, but making a choice is important, as you’ll likely want to have one dominant style in the codebase. Objects help to group and namespace functions, but there is additional complexity in sharing functions between objects.

If you’re tending toward an object-oriented codebase, what we had before is preferable. If your codebase is intended to be functional, you would probably opt for this, keeping in mind that you must keep the scope of the function small (likely through creating modules) in order to prevent name collisions. Additionally, you might wonder if the BinaryKnower and BinaryOblivious classes are needed. It is easy to make the case against them if they only contain one function:

function log(fun, number){ 
  console.log(fun(number));
};
function whatIsInBinary(number){return Number('0b' + number)};
function whatIs(number){return number};

[whatIsInBinary, whatIs].forEach(fun => { log(fun, 10) });

Presumably, in a real application, we’d have a bit more to our Person objects, which might justify using a class (or at least an object) rather than just the function as we did here. However, it’s also entirely possible to organize your code as a series of functions and return values. Look for opportunities to do both.

Since this chapter is primarily for the purpose of illustrating object-oriented patterns, we’ll ignore the functional variant for now.

Strategy

The template method pattern allowed us to remove a conditional through subclassing. The strategy pattern allows us to remove the subclasses by attaching a strategy (function) to the parent object.

Let’s take a look at what we have now:

class Person{
  log(number){ console.log(this.whatIs(number)) };
};

class BinaryKnower extends Person{
  whatIs(number){ return Number('0b' + number) };
};

class BinaryOblivious extends Person{
  whatIs(number){ return number };
};

const personOne = new BinaryKnower();
const personTwo = new BinaryOblivious();
[personOne, personTwo].forEach(person => person.log(10));

As we took a critical eye to the Person class in the last section, now let’s consider whether we need the subclasses. We could avoid them by setting a type value in the constructor and recreating the conditional in the whatIs function that we had earlier in the “test” code (logging output):

class Person{
  constructor(knowsBinary){
    this.knowsBinary = knowsBinary;
  };
  log(number){ console.log(this.whatIs(number)) };
  whatIs(number){
    if(this.knowsBinary){
      return Number('0b' + number);
    } else{
      return number;
    }
  };
};

const personOne = new Person(true);
const personTwo = new Person(false);

[personOne, personTwo].forEach(person => { person.log(10) });

We could eliminate this type check by adding functions to our personOne and personTwo objects after they are created:

class Person{
  log(number){ console.log(this.whatIs(number)) };
};

const personOne = new Person( );
personOne.whatIs = (number) => Number('0b' + number);
const personTwo = new Person(number => number);
personTwo.whatIs = (number) => number;

[personOne, personTwo].forEach(person => { person.log(10) });

Alternatively, we can eliminate the type check by supplementing the object with a function on construction:

class Person{
  constructor(whatIs){ this.whatIs = whatIs }
  log(number){console.log(this.whatIs(number)) }
};

const personOne = new Person(number => Number('0b' + number));
const personTwo = new Person(number => number);

[personOne, personTwo].forEach(person => { person.log(10) });

If we wanted, we could name and extract these functions to simplify the constructor:

function binaryAware(number){
  return Number('0b' + number);
};
function binaryOblivious(number){
  return number;
};

const personOne = new Person(binaryAware);
const personTwo = new Person(binaryOblivious);

Now that the functions are extracted, we can easily test them independently and without creating any Person objects.

You might be tempted to move these functions into the Person object, possibly as static functions like this:

class Person{
  constructor(whatIs){
    this.whatIs = whatIs;
  };
  log(number){
    console.log(this.whatIs(number));
  };
  static binaryAware(number){
    return Number('0b' + number);
  };
  static binaryOblivious(number){
    return number;
  };
};

const personOne = new Person(Person.binaryAware);
const personTwo = new Person(Person.binaryOblivious);

However, this is a level of coupling between the person (“context”) and binary awareness (“strategy”) that we’re trying to avoid. Binary awareness is potentially a strategy we’d like to give to other objects (e.g., dolphins, androids, and aliens) later, so it’s best to keep them separate.

Instead of that coupling, we can create a new object that contains the strategies, making the full code listing the following:

class Person{
  constructor(whatIs){ this.whatIs = whatIs };
  log(number){ console.log(this.whatIs(number)) };
};

const binary = {
  aware(number){ return Number('0b' + number) },
  oblivious(number){ return number }
};

const personOne = new Person(binary.aware);
const personTwo = new Person(binary.oblivious);

[personOne, personTwo].forEach(person => { person.log(10) });

Now our strategies are neatly tucked away in an object, which we pass to our new Person constructor. This is convenient, because if we create a new function representing a different interpretation of a number (say, octal or hexadecimal), it won’t require a whole new subclass.

You might notice that our “functional variant” from the template method section applies here as well. If we’re willing to drop objects and classes, we have a different (and usually shorter) type of code.

State

The state pattern is a bit more involved than the strategy pattern, but can flow naturally from it. Let’s assume that “awareness of binary” actually indicates knowledge of the binary operations read , and , and xor (exclusive or) as well. (There are other binary operations, but three are sufficient to demonstrate the pattern.) To continue to use the strategy pattern for this case, we would need to expand our constructor to include all of the new knowledge strategies:

class Person{
  constructor(readKnowledge, andKnowledge, xorKnowledge){
    this.read = readKnowledge;
    this.and = andKnowledge;
    this.xor = xorKnowledge;
  };
};

const binary = {
  readAware(number){
    return Number('0b' + number);
  },
  readOblivious(number){
    return number;
  },
  andAware(numberOne, numberTwo){
    return numberOne & numberTwo;
  },
  andOblivious(numberOne, numberTwo){
   return "unknown";
  },
  xorAware(numberOne, numberTwo){
    return numberOne ^ numberTwo;
  },
  xorOblivious(numberOne, numberTwo){
    return "unknown";
  }
};

const personOne = new Person(binary.readAware, 
                             binary.andAware,
                             binary.xorAware);
const personTwo = new Person(binary.readOblivious,
                             binary.andOblivious,
                             binary.xorOblivious);

[personOne, personTwo].forEach(person => {
  console.log(person.read(10));
  console.log(person.and(2, 3));
  console.log(person.xor(2, 3));
});

If we run this with node state.js (assuming we saved the file as state.js ), we’ll see the following output:

2
2
1
10
unknown
unknown

This expansion of the strategy pattern can get messy quickly. The easiest remedy to that is to allow two objects to contain all of the “obliviousness” or “awareness” of binary:

class Person{
  constructor(binaryKnowledge){
    this.binaryKnowledge = binaryKnowledge;
  }
};

const binaryAwareness = {
  read(number){
    return Number('0b' + number);
  },
  and(numberOne, numberTwo){
    return numberOne & numberTwo;
  },
  xor(numberOne, numberTwo){
    return numberOne ^ numberTwo;
  }
};

const binaryObliviousness = {
  read(number){
    return number;
  },
  and(numberOne, numberTwo){
    return "unknown";
  },
  xor(number){
    return "unknown";
  }
};

const personOne = new Person(binaryAwareness);
const personTwo = new Person(binaryObliviousness);

[personOne, personTwo].forEach(person => {
  console.log(person.binaryKnowledge.read(10));
  console.log(person.binaryKnowledge.and(2, 3));
  console.log(person.binaryKnowledge.xor(2, 3));
});

This simplifies the constructor calls and allows the binaryKnowledge to be independent of the person . Before we move on to fully implementing the state pattern, there are two additional possibilities worth consideration. The first is a potential shortcoming of all three functions being contained in the same knowledge objects. Is it possible for a person to know how to read binary, but not execute an xor operation? Sure, why not? This design doesn’t offer a flexible approach to that situation, but we’ll address that after completing the state pattern.

A second thing to consider is whether or not to add delegation from the person object directly to the binaryKnowledge functions, allowing for an interface like person.read or person.xor . There is a possible convenience in that, but it also has weaknesses. Tying those functions together in the constructor (using statements like this.read = binaryKnowledge.read ) would mean any new functions added to the binaryKnowledge objects would also need new references in the Person constructor. Additionally, the client code then masks the interfaces of the binaryKnowledge objects. Whether to delegate or not is going to come down to a matter of taste, but in general, the more dynamic and complex the delegate objects ( binaryKnowledge in this case), the more overhead and confusion you will have when delegating individual functions.

The binary object’s functions can be changed!

Although it’s convenient to attach objects directly to other objects like this, it is worth considering that although const will protect the value of binary from being reassigned, it does not prevent our aware or oblivious functions from being reassigned. Furthermore, if multiple person objects may reference the same function, redefining a function on a given person object will redefine the function for other objects as well. Adding the following code to the end should demonstrate this:

const personOne = new Person(binaryAwareness);
const personTwo = new Person(binaryAwareness);
personTwo.binaryKnowledge.read = () => `
redefined on both objects`;

[personOne, personTwo].forEach(person => {
  console.log(person.binaryKnowledge.read(10));
});

The easiest path to having immutable objects is to have new objects. We’ll address this toward the end of this section.

What makes this not quite yet the state pattern is that we haven’t defined the transitions between our objects. Let’s do that now:

class Person{
  constructor(binaryKnowledge){
    this.binaryKnowledge = binaryKnowledge;
  };
  change(binaryKnowledge){
    this.binaryKnowledge = binaryKnowledge;
  };
};

const binaryAwareness = {
  read(number){
    return Number('0b' + number);
  },
  and(numberOne, numberTwo){
    return numberOne & numberTwo;
  },
  xor(numberOne, numberTwo){
    return numberOne ^ numberTwo;
  },
  forget(person){
    person.change(binaryObliviousness);
  }
}
const binaryObliviousness = {
  read(number){
    return number;
  },
  and(numberOne, numberTwo){
    return "unknown";
  },
  xor(number){
    return "unknown";
  },
  learn(person){
    person.change(binaryAwareness);
  }
};

const personOne = new Person(binaryAwareness);
const personTwo = new Person(binaryObliviousness);

[personOne, personTwo].forEach(person => {
  console.log(person.binaryKnowledge.read(10));
  console.log(person.binaryKnowledge.and(2, 3));
  console.log(person.binaryKnowledge.xor(2, 3));
});

personOne.binaryKnowledge.forget(personOne);
personTwo.binaryKnowledge.learn(personTwo);

[personOne, personTwo].forEach(person => {
  console.log(person.binaryKnowledge.read(10));
  console.log(person.binaryKnowledge.and(2, 3));
  console.log(person.binaryKnowledge.xor(2, 3));
});

This requires one new function ( change ) to be defined on Person , as well as a forget function defined on binaryAwareness and a learn function defined on binaryObliviousness . For our tests (just logging statements) we flip the binary knowledge states of our two person objects and should see the output reversed when it prints the second time.

There are two things about this code that are suspect. First, it is awkward to pass a person object into the forget and learn functions. Second, as the warning text previously indicated, our binaryKnowledge objects are not safe from being redefined.

We could address the second problem by making factory functions, constructor functions, or classes that would return our binaryKnowledge objects. However, a simpler solution is just to wrap our assignment to binaryKnowledge in the Person constructor with an Object.create . To make our change function safe, we can wrap it as well:

class Person{
  constructor(binaryKnowledge){
    this.binaryKnowledge = Object.create(binaryKnowledge);
  };
  change(binaryKnowledge){
    this.binaryKnowledge = Object.create(binaryKnowledge);
  };
};

To solve the first problem (the awkwardness of duplicating our references to person in the learn and forget functions), we can use Object.assign in the Person constructor to establish a two-way link between binaryKnowledge and the person object. Then we can remove the parameter from both forget and learn , and change the references to that parameter to instead use this.person :

class Person{
  constructor(binaryKnowledge){
    this.binaryKnowledge = Object.create(
                             Object.assign(
                               {person: this},
                                binaryKnowledge));
  };
  change(binaryKnowledge){
    this.binaryKnowledge = Object.create(
                             Object.assign(
                               {person: this},
                                binaryKnowledge));
  };
};

const binaryAwareness = {
...
  forget(){
    this.person.change(binaryObliviousness);
  }
}
const binaryObliviousness = {
...
  learn(){
    this.person.change(binaryAwareness);
  }
};

const personOne = new Person(binaryAwareness);
const personTwo = new Person(binaryObliviousness);

...

personTwo.binaryKnowledge.forget();
personTwo.binaryKnowledge.read = () => 'will not assign both';
[personOne, personTwo].forEach(person => {
  console.log(person.binaryKnowledge.read(3));
});

The last five lines of this code snippet should confirm that the new reference to read stays within its own object and forget (as well as learn ) no longer requires an explicit argument for person .

Alternatively, we could define both forget and learn on the Person class (the original design pattern does not specify where transitions are defined), but the issue raised earlier about delegating functions to Person also applies now: if we add information about states to Person , then Person becomes more complex and less focused. That said, it may be worth it in some cases in order to centralize transition information.

State Pattern Versus State Machine

There is a bit of crossover between the state pattern and the state machine . Although the ideas are related, state machines tend to focus on the states themselves and transitions between them, rather than providing a unified interface for common functions. Although you gain some simplicity by virtue of having just one class/object controlling all of your states and transitions (and typically callback functions to execute during transitions as well), you lose the simplicity of a unified interface while in any given state. That means more type checking ( if statements), and is a likely place for complexity to accumulate over time.

And now, some unfortunate news about the state pattern.

Here, we had a fairly simple example of the pattern, with only two states. Although it scales fairly well, refactoring to use the state pattern just for the sake of removing conditional checks is fairly aggressive once a codebase has headed down the path of lots and lots of type checking (whether with or without a state machine in place). And adding a lot of new objects/classes (one for each state) might not be a popular idea among your teammates.

You can also encounter problems if your states are complex. Picture a branching structure where “knowing xor ” is a substate of “knowing binary,” which is a substate of “knowing math,” which is a substate of “understanding the universe.” If your states branch out like that, you’ll be overwhelmed with classes/objects very quickly. Put another way, it’s possible that your states may have nothing to do with one another. Do you make a state for every combination of “knowing binary,” “knowing English,” and “having a pet”? Do you introduce another full-blown state pattern implementation for each independent type of state? Hopefully, the answer is no, and simplicity wins over competing types of states for one type of object.

One final thing that the classical state pattern comes with is some contract that a certain interface is implemented by each state class/object. We have made no such guarantee in our usage. In JavaScript, without compile-time checks for such contracts, we have a couple of options. We could use assertions inside of constructors for our states or our context ( Person ). We could create a BaseState object that contains stubs of functions (and possibly throws an error if they are not overwritten). Or we could do nothing to enforce that type of contract. Given our options, this isn’t that bad. We’ll get TypeError: _someObject.whatever_ is not a function errors, which is probably as descriptive as any error we would throw in the BaseState or an AssertionError we would get from failed assertions in the constructors. Another option is using a language that compiles to JavaScript and has these features (like TypeScript). Hopefully, the appeals to simplicity in this chapter make it clear that it is not advisable to rewrite your entire program in a different language and complicate your build process for the sake of fully realizing a design pattern.

The power of has-a

At the core of the state pattern is a willingness to move part of what may be thought of as “belonging to” an object into another. There is a tendency in OOP to prioritize hierarchies over delegate objects. The state pattern is a relatively complex version of delegation, but simpler delegate objects should not be overlooked.   

null Object

The null object pattern, unlike the others discussed here, was not one of the original 23 patterns defined in the Gang of Four’s book Design Patterns: Elements of Reusable Object-Oriented Software —and is probably the most underused of all. Consider how many conditional checks in your code are executed against null , undefined , or the existence of a particular variable or function. Odds are, that type of checking makes up a large portion of your if statements. And worse, the absence of those type checks likely accounts for a large portion of your errors.

A (Non-)Value Not Even a Father Could Love

Tony Hoare invented the null reference in 1965. In 2009, he called it his “billion dollar mistake” because of all the damage it has caused. Considering not only runtime errors, but all of the extra time spent coding type checks for null values across every language that has implemented it, a billion dollars is probably an understatement.

In fact, according to research from Cambridge University in 2013 (admittedly sponsored by a bug-hunting software vendor), bugs cost the world $316 billion dollars every year. Surely, not all of those derive from improper handling of null conditions, but from my personal experience with web applications, I would guess that it accounts for a significant portion. If I was hard-pressed for a percentage, I’d estimate somewhere around half, assuming no static typing tools are in place. It’s certainly more than 1 in 316, and we’re talking about annually here.

Hoare’s career is a distinguished one, so this is not brought up to criticize him. The point is that “ null is a billion-dollar mistake” is not common enough knowledge for people to avoid using it. It (and undefined ) didn’t make Crockford’s list of “bad parts” (Appendix B in JavaScript: The Good Parts ), and it is returned by so many APIs in so many libraries.

Let’s start with something that might return null :

class Person {
  constructor(name){
    this.name = name;
  }
};
class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = null;
  }
};

personOne = new Person("tony");
personTwo = new AnonymousPerson("tony");
console.log(personOne.name);
console.log(personTwo.name);

One unfortunate distraction in this code is the call to super in the constructor of the subclass. If you don’t call super , you’ll get a  ReferenceError: this is not defined , which not only is an unclear error, but also demonstrates how null or undefined can come from core parts of the language, not just libraries.

Regardless, the output doesn’t look so bad:

tony                                                                                                                                                                   
null

But let’s say we want to do something with those values:

function capitalize(string) {
  return string[0].toUpperCase() + string.substring(1);
};

console.log(capitalize(personOne.name));
console.log(capitalize(personTwo.name));

Now our trouble starts with:

TypeError: Cannot read property '0' of null

We might be inclined to try to solve this by using an empty string instead of null :

class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = "";
  }
};

This time, we’ll get a new error:

TypeError: Cannot read property 'toUpperCase' of undefined

It’s just as bad as the first one, so we might as well put our null back. Now we’re stuck doing some type checking inside of capitalize :

function capitalize(string) {
  if(string === null){
    return null;
  }else{
    return string[0].toUpperCase() + string.substring(1);
  }
};

Because we didn’t have a good way out of the empty value we got from the AnonymousPerson name property (we’re pretending we don’t know about null objects), we’re stuck with some kind of nonsensical type check like this (it could just as easily be "" or undefined ). And the consequence for not type checking is that our program will throw an error at runtime.

So what do we do if the string is null ? We might as well return another null . Now say we want to tigerify our tony s:

function tigerify(string) {
  return `${string}, the tiger`;
};
console.log(tigerify(capitalize(personOne.name)));
console.log(tigerify(capitalize(personTwo.name)));

Now our output is:

Tony, the tiger                                                                                                                                                        
null, the tiger

Well, it’s not an error, but that’s not a value we want to display. Let’s try this:

function tigerify(string) {
  if(string === null){
    return null;
  }else{
    return `${string}, the tiger`;
  }
};

Now we’ll get just plain null for the string, which isn’t really a better value to display than before. We don’t really want to make our tigerify function responsible for the final output (it’s nice that capitalize and tigerify have the same interface, as we can call both in either order, or one without the other), so let’s create a display function to handle the finalized output:

function display(string){
  if(string === null){
    return '';
  }else{
    return string;
  }
};

Then we run another null check so that we can display a blank string.

But No One Would Actually Display null, Right?

Yeah, they would. I’m not going to say what website I saw Figure 9-1 on, but they have over $40 million in funding. Also, they created the null here, not me.

Figure 9-1. A display of null in the wild

Hopefully, the antipattern is becoming clear: either check for null , or subject people to errors and other awkward interactions. It takes one null to kick off a codebase full of conditional checks and sadness. Not only does every function that calls something that could return a null value likely need a null check, but your tests are necessarily more complex as well, because any functions you test will have at least two branches.

So how do we fix it? The answer is we start treating our names like objects, rather than strings and null s. Then we can begin to implement functions that have a mirror interface:

class Person {
  constructor(name){
    this.name = new NameString(name);
  }
};
class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = new NullString;
  }
};

class NullString{
  capitalize(){
    return null;
  }
};

class NameString extends String{
  capitalize() {
    return new NameString(this[0].toUpperCase() + this.substring(1));
  };
  tigerify() {
    if(this === null){
      return null;
    }else{
      return new NameString(`${this}, the tiger`);
    }
  };
  display(){
    if(this === null){
      return '';
    }else{
      return this.toString();
    }
  };
}

personOne = new Person("tony");
personTwo = new AnonymousPerson("tony");
console.log(personOne.name.capitalize().tigerify().display());
console.log(personTwo.name.capitalize());

The biggest change here is the addition of two new classes: NameString and NullString . The Person and AnonymousPerson constructors create these objects. Notice that we’re now chaining functions instead of nesting them, and that display now calls toString so that console doesn’t print the type information. NameString implements our functions as before (except for the type check we could remove from capitalize , but NullString only has capitalize implemented right now).

Why is that?

Because the traditional way to implement the null object pattern is to return null . We hit the null wall and can’t do anything else with personTwo without type checking. It’s worth stopping there for a minute to think about how unfortunate that is.

Now let’s do something better. We’ll implement a NullString that not only has mirror functions, but also returns mirror values to the NameString .

Why didn’t we just overwrite String.prototype?

Overwriting base objects is considered a likely bad idea unless you’re sure that the changes are desirable for some scope that’s easy to contain. Most of the time, other programmers (also you, after you’ve forgotten that you overwrote parts of String ) will assume that it is the same String that they’re used to. Although subclassing is usually worse than other options for extracting an object, it is very useful for creating copies of native objects like String and Array .

Our code looks like this with mirror interfaces:

// with null object
class Person {
  constructor(name){
    this.name = new NameString(name);
  }
};

class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = new NullString;
  }
};

class NullString{
  capitalize(){
    return this; // same as new NullString in this case
  };
  tigerify() {
    return this; // same as new NullString in this case
  };
  display() {
    return '';
  };
};

class NameString extends String{
  capitalize() {
    return new NameString(this[0].toUpperCase() + this.substring(1));
  };
  tigerify() {
    return new NameString(`${this}, the tiger`);
  };
  display(){
    return this.toString();
  };
}

personOne = new Person("tony");
personTwo = new AnonymousPerson("tony");
console.log(personOne.name.capitalize().tigerify().display());
console.log(personTwo.name.capitalize().tigerify().display());

Some people claim that this is more complicated than the equivalent version. Let’s look at the other for reference:

// without null object
class Person {
  constructor(name){
    this.name = name;
  };
};
class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = null;
  };
};

function capitalize(string) {
  if(string === null){
    return null;
  }else{
    return string[0].toUpperCase() + string.substring(1);
  }
};

function tigerify(string) {
  if(string === null){
    return null;
  }else{
    return `${string}, the tiger`;
  }
};

function display(string){
  if(string === null){
    return '';
  }else{
    return string;
  }
};

personOne = new Person("tony");
personTwo = new AnonymousPerson("tony");

console.log(display(tigerify(capitalize(personOne.name))));
console.log(display(tigerify(capitalize(personTwo.name))));

It’s actually about the same number of lines. Is it better to have a conditional in every function or to have two functions in different classes? Now that we see them side by side, let’s talk about the pros and cons of using the null object pattern:

Pros:

  • You can use console.log and actually find out something about your values.
  • You can do anything you want in the function body.
  • You can have the null object inherit and override functions (from NameString ).
  • It’s very easy to forget to do a null check. Having a complete API to duplicate may seem more straightforward to you.

Cons:

  • You might have the classes in two separate files by convention, creating overhead in searching the project.
  • You might buck the convention of separating them by having them in the same file. This also creates overhead in searching the project.
  • You might have teammates who don’t like the idea of null objects, don’t understand the idea of null objects, or just don’t care about null objects (this is the case with pretty much every pattern or quality concern in general).
  • Since null and undefined are so commonly returned, your codebase is unlikely to be completely null / undefined free. That means you will probably end up with inconsistencies and some confusion from people unfamiliar with the patterns you implement.
  • Because returning null / undefined is so common, if you want consistent expectations for not returning null / undefined , you’ll likely need to adapt a lot of your codebase as well as third-party APIs.
  • You have to implement a function on the null object every time you create a new function call that might call the null object instead of its mirrored real one. Since it’s likely that you’d have to add and might forget a null check (if you’re not using null objects), I think this one is a wash.
  • You can’t insist that third-party code follow sane practices for returning real values. If you’re stuck with a library that returns the billion-dollar mistake, you’ll need to wrap that interface with a new functionality, which could be confusing to people used to working with the basic interface.
  • You might want different null object functions depending on the eventual context of how the value will be used. Will it be saved to the database? Logged? Used to create a new value? These all suggest different terminal functionality (such as our display function).
  • When working with native object types such as strings and arrays, you’ll face overhead in extending them to build subclasses to mirror the null objects.

Overall, in application development, the null object pattern provides an alternative to null checks (and the errors caused when you forget to check for null ). If you’re writing a library, framework, or module , however, it is worth considering this pattern in order to avoid “ null -poisoning” the codebases of anyone who uses your code.

If you’re trying to avoid all of the subclasses involved in this pattern, you can try combining it with the techniques presented in the sections for the state and strategy patterns. Also, in Chapter 11 , we’ll look at a functional alternative to the null object pattern called Maybe . As for the next section, we’ll double down on the null object pattern by combining it with a wrapper.

Wrapper (Decorator and Adapter)

There are a few ways to implement the decorator pattern. One thing that should not be surprising based on earlier sections in this chapter is that JavaScript does not naturally fit in well with interfaces, abstract classes, and other object-oriented language features that tend to be a part of the classical pattern.

Before moving on, install tape with npm install tape . It’s a more lightweight test framework than mocha. We’ll use it again in Chapter 10 .

Most of the time for the decorator pattern, you’ll see an example like this:

class Dog{
  constructor(){
    this.cost = 50;
  }
  displayPrice(){
    return `The dog costs $${this.cost}.`;
  }
};

const test = require('tape');
test("base dog price", (assert) => {
  assert.equal((new Dog).displayPrice(), 'The dog costs $50.');
  assert.end();
});

This is not the same assert as before

tape has a special callback parameter that has an assertion syntax built in. It’s also responsible for ending the test and counting the test cases. If we use a different assertion library in tape, we have to add an extra assert.pass() line, which is awkward:

const test = require('tape');
const wish = require('wish');
test("base dog price", (assert) => {
  wish((new Dog).displayPrice() 
=== 'The dog costs $50.');
  assert.pass();
  assert.end();
});

If we don’t add that line, the tests won’t fail , but tape won’t count them as passing, or even as tests(!), in its output. We’ll stick with tape’s assert in this chapter.

The decorator is useful in a couple of cases. First, it’s good if we’re pulling the dog class in from a module we don’t own and don’t want to (or can’t) manipulate it directly. Second, it’s good to keep us from a sprawling mass of subclasses. To illustrate that second point, consider if our price was based on whether the dog was cute, trained, robotic, friendly, or a show dog. All of those traits could affect the price, but they are not mutually exclusive, so comprehensive subclassing would have to collect every attribute (e.g., class FriendlyNotCuteTrainedNonRoboticNonShowDog extends Dog ).

To decorate the dog with a particular trait, we can add a factory function that takes a dog as input:

function Cute(dog){
  const cuteDog = Object.create(dog);
  cuteDog.cost = dog.cost + 20;
  return cuteDog;
};

test("cute dog price", (assert) => {
  assert.equal((Cute(new Dog)).displayPrice(), 'The dog costs $70.');
  assert.end();
});

Adding another trait is as simple as adding a new factory function:

function Trained(dog){
  const trainedDog = Object.create(dog);
  trainedDog.cost = dog.cost + 60;
  return trainedDog;
};
test("trained/cute dog price", (assert) => {
  assert.equal(Trained(Cute(new Dog)).displayPrice(),
               'The dog costs $130.');
  assert.end();
});

We can add new decorators like this quite easily.

Do we have to nest the factory functions?

You might be wondering if we could get away with an interface like this instead:

(new Dog).Cute().Trained();

The answer is “yes, we absolutely could do that.” However, can we do that without adding new functionality to the original class? No. One major point of this pattern is that we either can’t or don’t want to alter the original class.

The “cost of something” decorator focuses on adding traits to an existing interface. In other cases, we want to adapt an interface by applying another wrapper. Let’s try addressing the problem of an API that returns null s, “billion-dollar mistakes” that they are (see the previous section if you need some background on null objects). Here is some code similar to what we looked at in the previous section (before we made the null objects):

class Person {
  constructor(name){
    this.name = new NameString(name);
  }
};

class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = null;
  }
};

class NameString extends String{
  capitalize() {
    return new NameString(this[0].toUpperCase() + this.substring(1));
  };
  tigerify() {
    return new NameString(`${this}, the tiger`);
  };
  display(){
    return this.toString();
  };
};

const test = require('tape');

test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(personOne.name.capitalize().tigerify().display(),
               'Tony, the tiger');
  assert.end();
});

This works fine, but if we want to test AnonymousPerson objects, we’re stuck handling the null checks in our test. To be explicit, add this test:

test("Displaying an anonymous person", (assert) => {
  const personTwo = new AnonymousPerson("tony");
  assert.equal(personTwo.name.capitalize().tigerify().display(),
               '');
  assert.end();
});

We’ll quickly hit this error:

TypeError: Cannot read property 'capitalize' of null

In our null object example from the last section, we dealt with this by allowing AnonymousPerson to return a NullString for name and then added some functions to NullString . It would be convenient if we could add the following code (changing AnonymousPerson and adding NullString ):

class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = new NullString; // this line is the problem
  }
};
class NullString{
  capitalize(){
    return this;
  };
  tigerify() {
    return this;
  };
  display() {
    return '';
  };
};

Let’s say that we can’t touch AnonymousPerson , but we have no problem adding the NullString class for the sake of applying this decorator pattern.

With what we need to add, our code becomes the following:

class Person {
  constructor(name){
    this.name = new NameString(name);
  }
};

class AnonymousPerson extends Person {
  constructor(){
    super();
    this.name = null;
  }
};

class NameString extends String{
  capitalize() {
    return new NameString(this[0].toUpperCase() + this.substring(1));
  };
  tigerify() {
    return new NameString(`${this}, the tiger`);
  };
  display(){
    return this.toString();
  };
};

// this is new
class NullString{
  capitalize(){
    return this;
  };
  tigerify() {
    return this;
  };
  display() {
    return '';
  };
};

// this is new
function WithoutNull(person){
  personWithoutNull = Object.create(person);
  if(personWithoutNull.name === null){
    personWithoutNull.name = new NullString;
  };
  return personWithoutNull;
};

const test = require('tape');

test("Displaying a person", (assert) => {
  const personOne = new Person("tony");
  assert.equal(personOne.name.capitalize().tigerify().display(),
               'Tony, the tiger');
  assert.end();
});

test("Displaying an anonymous person", (assert) => {
  const personTwo = new AnonymousPerson("tony");
// wrapping with WithoutNull is new
  assert.equal(WithoutNull(personTwo)
               .name.capitalize().tigerify().display(),
               '');
  assert.end();
});

And both tests pass. We just had to add the WithoutNull function and use it to wrap personTwo . All it does is prevent name from being null . Because it does not convert the name unless it is null , we can happily wrap any person object with WithoutNull , anonymous or not. Notice that we use a simple factory function that returns an object, but we could have used a class or constructor function instead. The disadvantage of those approaches is that they implicitly return an object, and here, it’s easier to explicitly return a new one that we construct manually. With a class or constructor function, the implicitly returned class would be of type WithoutNull , which is odd, and overriding it (returning a different object in the constructor function of the class or from a constructor function called with new ) reads as a bit confusing.

Two other things are worth considering here. First, it won’t always be the case that we can decide what type of person object we have. It’s possible that we’d only have one type of Person and we would not be able to determine ahead of time whether or not it had a name (or any other attributes that we might wrap with WithoutNull ). For example, we might be receiving objects from the database with a function like (db.get({person: {id: 17}})) . Our WithoutNull wrapper would be excellent for providing a consistent interface to name and other attributes just by wrapping the call like this: withoutNull(db.get({person: {id: 17}})) . It’s very likely that we would not want to change the database API itself, but rather wrap values that it returns.

Second, if our API returned a string instead of a real object for name in the normal Person case (rather than a NameString ), we would have had much more difficulty in setting up a parallel function structure for NullString without directly extending our “untouchable” Person and AnonymousPerson classes, overwriting String.prototype , or compromising our fairly simple wrapping API.

We’ve seen two possible interfaces so far:

Cute(dog);
WithoutNull(personTwo);

As we noted earlier, we could have used a class/constructor function instead of a factory function, which would give us an interface like:

new Cute(dog);
new WithoutNull(personTwo);

The reason we didn’t do that is that it is odd to explicitly return something from a constructor function (which carries the expectation of returning the type of object named by the constructor or class).

From the perspective of an interface, what is a new Cute ? What is a new WithoutNull ? These are traits, and don’t really make sense to instantiate. So it’s not only the implementation, but also the interface, that suggests a factory function.

For another take on this, let’s look at a very simple adapter that uses a class:

class Target{
  hello(){
    console.log('hello');
  };
  goodbye(){
    console.log('goodbye');
  };

};
class Adaptee{
  hi(){
    console.log('hi');
  };
  bye(){
    console.log('bye');
  };
};

const formal = new Target;
formal.hello();
formal.goodbye();

const casual = new Adaptee;
casual.hi();
casual.bye();

class Adapter{
  constructor(adaptee){
    this.hello = adaptee.hi;
    this.goodbye = adaptee.bye;
  };
};
const adaptedCasual = new Adapter(new Adaptee);
adaptedCasual.hello();
adaptedCasual.goodbye();

So we have casual and formal objects with different interfaces ( hi versus hello , and bye versus goodbye ). If we need to support the same interface, Adapter can remap the functions to new ones. This is the same problem that WithNull helped us solve earlier .

For the same reasons as with the decorators, Adapter would probably be best as a factory function. But if we use a factory function for the adapter, what is the difference between an adapter and a decorator?

The “decorator” TC39 proposal

There are, as of this writing, a few proposals for JavaScript features that use the term decorator . Although they are distinct from our discussion here, they involve similar ideas of altering existing behavior.

The difference is one of emphasis and likely usage. A decorator is more likely to have nested wrappers to add a few disparate traits. An adapter is more of a mapping of interfaces between one object and another. Imagine our WithNull implementing a conversion of every property to not allow for null . In a decorator scenario, we might prefer to nest as in WithoutNullName(WithoutNullPhone(person))) . For an adapter, we would be more likely to apply the interface transformation as a necessary and single step. So the dog example was probably more of a decorator, while the “without null ” example was more of an adapter. But does it matter? Not really. In all cases, we’re using wrapper functions to add properties to objects. It’s tempting to think of patterns in terms of “interfaces” (the OOP term) and “abstract classes,” subclasses and private/public methods and members, but JavaScript isn’t Java. UML diagrams to describe these complex relationships can be a useful starting point for design, but for JavaScript, your best option is to start  with the interface (the test/client code) you want to write and then figure out how to implement it.

When should we avoid decorators and adapters?  Well, if we have control over the entire implementation (i.e., we own our own libraries), we might get the same utility from altering the base code rather than complicating our interfaces with wrapping possibilities. Additionally, as with applying any pattern, ensure that the result is actually simpler and more understandable than the original (unpatterned) code. Before using the adapter function, first try extracting objects and functions. If you still want to apply the pattern, this will probably just make the process easier. 

Facade

After the more challenging wrapper patterns, the facade is extremely simple. We have some complex API, but instead of interacting with it directly, we use an interface. When you play a piano, you’re not physically pushing the hammers into the strings. When you drive a car, you’re probably focused on the destination or next high-level step, occasionally thinking about your controls, and rarely (if ever) thinking about the internal components.

Basically, a facade is an interface that contains a curated subset from one or more APIs with the intention of streamlining and simplifying the code one needs to write.

As for a more specific software example, let’s consider how JavaScript interacts with native web APIs. The number of properties available on document and window alone is huge, and it can hardly be recommended that a beginner just read the documentation in order to get a handle on how they work.

Let’s create a facade that demonstrates the kinds of things you can do with JavaScript. Since we’ll be interacting with a browser, we can start with an HTML page and save it as facade.html :

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; 
     charset=utf-8" />
    <title></title>
    <script type="text/javascript" src='facade.js'></script>
  </head>
  <body>
  </body>
</html>

In the same directory, we can add a file for facade.js :

const page = {
  say(string){
    console.log(string);
  },
  yell(string){
    alert(string);
  },
  addNewLine(){
    document.body.appendChild(document.createElement("br"));
  },

  addButton(text){
    const button = document.createElement("button");
    button.appendChild(document.createTextNode(text));
    document.body.appendChild(button);
  },
  addText(text){
    const span = document.createElement("span");
    span.appendChild(document.createTextNode(text));
    document.body.appendChild(span);
  },
  changeBackground(color){
    document.body.style.background = color;
  },
  now(asNumber = false){
    if(asNumber === false){
      return new Date().toLocaleTimeString();
    }else{
      return new Date().getTime();
    }
  },
  timeOnPage(){
    return ((this.now(true) - this._start) / 1000) + " seconds";
  },
  loadTime(){
    return ((this._start - this._loaded) / 1000) + " seconds";
  },
  eventsSoFar(){
    console.info(this._events);
  },
  _events: [],
  _start: 'nothing yet',
  _loaded: 'nothing yet'
};

window.onload = function(){
  page._start = page.now(true);
  page._loaded = performance.timing.navigationStart;
  document.onclick = function(event) {
    page._events.push(event.target + " clicked at " + page.now());
  };
};

In this file, we’re making the following functions available:

  • say ( console.log )
  • yell (alert)
  • addNewLine (adds <br> tag)
  • addButton (adds a button)
  • addText (adds a paragraph)
  • changeBackground (changes background to a color)
  • now (prints the current time, nicely formatted with default parameter)
  • timeOnPage (how many seconds someone has been on the page)
  • loadTime (how long it took the page to load)
  • eventsSoFar (what the visitor has clicked on)

If you want to try it out, open facade.html in a browser. We have black box functions on an object called page . All it does is put together a limited subset of how you might interact with a website, including the basics of logging, analytics, page interactions, and performance monitoring. This could be useful for someone unfamiliar with browser APIs or the browser console.

When should you not use a facade? Any time the direct interactions with an API are simple enough or understood well enough by you or other people interacting with it. In those cases, adding a facade is a bad idea, because it either will not be used, or will be used sometimes , leading to learning/supporting/understanding/maintaining two disparate interfaces.

Facades are widely used for tasks like simplifying complex APIs. ORMs (object relational mappers) can be useful for simplifying database interactions. And jQuery is arguably a very large facade for frontend JavaScript and all the APIs it interacts with. Once you get to the ORM or framework level, you’ve got a lot more going on than a simple “facade,” but the intention is the same.

It is tempting to think of interfaces strictly in terms of public/private (which in JavaScript could mean prepended with _ , completely hidden, or a couple of other things). However, exposing a smaller subset of an API is underutilized. Consider that we’ve already seen one clear example of why we might use a less feature-rich API over a complex one (tape versus mocha). Whether for convenience or learning, exposing a core/popular set of features independently from a large API could make documentation and coding easier on beginners (and “forgetters”)—which, considering how massive the JavaScript landscape is, includes practically everyone.

What Does the Alphabet Have to Do with APIs?

Even without the creation of a distinct, smaller interface for an API through a facade, people deserve better than documentation organized only alphabetically. What are the most useful functions? What are the most popular?

These are not impossible questions to answer. By providing a subset of documentation or allowing functionality to be ranked by something more practical than the alphabet, advice to “RTFM” would be a lot more useful, albeit just as rude.

Wrapping Up

We’ve left out the majority of the patterns from the seminal design pattern book, Design Patterns: Elements of Reusable Object-Oriented Software (also known as the “Gang of Four” or “GoF” book for its four authors), as well as a good number of those that have popped up throughout the years. Since this is a refactoring book and not a patterns book, we had to draw the line somewhere, especially given that the term pattern is used as freely and casually as refactoring can be. Additionally, our goal is turning bad (and likely to be seen) code into good code. Sometimes, there is simply not a plausible form that code could take as a “before” case. In other instances, applying a pattern is done for the sake of optimization, rather than to achieve a better interface. Another reason some patterns are not included is that they’re built into JavaScript itself.

With those thoughts in mind, a few additional patterns worth exploring are:

Composite

This pattern is good for traversing trees of data, such as JSON/objects/document nodes.

Builder

Used for complex object creation, this pattern is good for generating test data.

Observer

This pattern can be seen in things like publish/subscribe, events, and observables.

Prototype

This pattern is built into JavaScript.

Iterator

Building your own iterator is an unlikely choice given the wealth of native options for iteration (including loops, array comprehension functions, and generators ).

Proxy

We actually see an example of this in action in Chapter 10 when we use the testdouble framework, which allows “faking out” the real function call as well as asserting that the function was called. Note that there is also a native proxy object in JavaScript, and it is another possible approach to wrapping an object with withoutNull , as we covered earlier.

The GoF book doesn’t have a monopoly on design patterns, nor do object-oriented languages or web applications. In some languages or problem domains, a pattern might be very popular or easy to implement. JavaScript, given that it spans so many paradigms and applications, has a large pool of architectural ideas to draw from. If you are looking for some new patterns to think about, embedded programming, operating systems, databases, concurrency, functional programming, and game development might be of interest.

In this chapter, we looked at some of the best that object-oriented architecture has to offer, through a JavaScript lens. For the sake of refactoring, and coding generally, the advice from the GoF to “program to an interface, not an implementation” rings true. Between (our) JavaScript’s lack of a distinct compilation step and some keywords that didn’t cross over from Java, SmallTalk, and the like, this is not only practical advice, but the only possible approach for implementing many patterns.

Ultimately, even if perfectly implementing UML diagrams from other languages were possible with JavaScript, the patterns presented in this chapter are intended to address likely architectural problems. Specifically, we addressed maintenance issues that arise with code complexity (exemplified by the proliferation of conditionals and subclasses), learned how to avoid “billion-dollar mistakes” from external code, and provided an example of how to create a small, friendly API.

In the next two chapters, we will be exploring JavaScript’s more functional side.

1 Disclaimer: Life changes may be somewhat subtle.