In the previous two chapters, we saw a large example of refactoring in action. Ultimately, our concern was with the execution of two main actions: training and classifying. It was convenient to write our program as having one main object (a Naive Bayes Classifier), which was also explored as a class and a module.
For this chapter, one object is not enough.
About “CRUD Apps” and Frameworks
As a web application developer, you’d likely spend a lot of time with “CRUD” (create, read, update, delete) applications. That means concentrating on two high-level tasks: organizing data, and presenting that data.
The former is often addressed by database management systems (and your design of the data), while the latter is often handed off to a framework, concerned with the efficient and workable presentation of that data. Database records mix together with some proprietary data, and turn into CSV (comma-separated value) files and styled web pages.
Although we’re not diving into full-stack or presentation frameworks here, it is worth pointing out that they help to avoid a good deal of the problems that refactoring helps to solve. These include:
- One huge file containing all of the code
- One huge (flat) directory containing all of the code
- One huge object or function containing all of the code
As we demonstrated in the previous chapter, extracting functions, objects, and modules can provide some clarity into how the code works. Frameworks, databases, and other libraries provide common interfaces for data access and presentation, and in doing so, seem to solve the biggest organizational problems.
However, three major drawbacks to frameworks are:
- Even if the interface in your app becomes more standardized or “simplified” within a framework, team members will need to come up to speed.
- “Refactoring with framework x” is a rewrite. There’s no such thing as “refactoring” by radically changing interfaces.
- Developers can become (or begin as) completely dependent on frameworks, which constrains experience in the language itself.
This last point is as troubling as it is common. Many developers can use jQuery, React, and the like to some degree, but struggle with JavaScript outside of those contexts.
In Chapters 6 and 7 , we discussed the building blocks of architecting JavaScript in a reasonable way. In this chapter and beyond, we take those ideas a bit further, and in this chapter, we will discuss how hierarchies can go wrong.
There are definitely cases where you will want a framework to help you organize and standardize your code, but extracting functions, objects, and modules, as well as building hierarchies, are all tools that you should consider along with frameworks when you need to manage complexity.
Let’s Build a Hierarchy
In this chapter, we’ll be dealing with words—specifically, creating a vocabulary list. This could be a simple array of words you need to study, or, to add a bit of complexity, words could each be objects with multiple properties: aspects of state (nonfunction attributes) and behavior (functions).
As far as the motivation for hierarchy, there are two. The first is that having a “parent” object (and possibly class as well) will lend itself to code reuse and less repetition in code. Let’s say we want to count the characters of our words, for which we have two classes:
class EnglishWord{
constructor(word){
this.word = word;
}
count(){
return this.word.length;
}
};
class JapaneseWord{
constructor(word){
this.word = word;
}
count(){
return this.word.length;
}
};
const japaneseWord = new JapaneseWord("犬");
const englishWord = new EnglishWord("dog");
console.log(japaneseWord.word);
console.log(japaneseWord.count());
console.log(englishWord.word);
console.log(englishWord.count());
We can see that there is a lot of duplication in the classes, but what can we do about it?
class Word{
constructor(word){
this.word = word;
};
count(){
return this.word.length;
};
};
class EnglishWord extends Word{};
class JapaneseWord extends Word{};
const japaneseWord = new JapaneseWord("犬");
const englishWord = new EnglishWord("dog");
console.log(japaneseWord.count());
console.log(japaneseWord.word);
console.log(englishWord.count());
console.log(englishWord.word);
Now EnglishWord and JapaneseWord both inherit from Word , and the code is much shorter. We’ve “extracted a superclass” and “pulled up the functions” from the subclasses. If the subclasses were actually the same, we’d be free to delete those two classes (collapsing the hierarchy) completely and just use new Word(" _something_ ") for new words. However, we’ll be adding distinguishing features to both, so let’s keep them for now.
As far as distinguishing features of these different words, they won’t tend to appear in the same dictionary. Should we want to look them up, we could add a function to our superclass ( Word ) like this:
class Word{
...
lookUp(){
if (this instanceof JapaneseWord){
return `http://jisho.org/search/${this.word}`;
}else{
return `https://en.wiktionary.org/wiki/${this.word}`;
}
};
};
...
console.log(englishWord.lookUp());
console.log(japaneseWord.lookUp());
The instanceof operator is something we haven’t seen yet (by the way, the unfortunate lack of camelCase is not a typo). It can be handy, but ties our conditional to a specific name of the class. To get away from that, we might want to add a language attribute to each class of word:
class Word{
constructor(word){
this.word = word;
};
count(){
return this.word.length;
};
lookUp(){
if (this.language === "Japanese"){
return `http://jisho.org/search/${this.word}`;
}else{
return `https://en.wiktionary.org/wiki/${this.word}`;
}
};
};
class EnglishWord extends Word{
constructor(word){
super(word);
this.language = "English";
};
};
class JapaneseWord extends Word{
constructor(word){
super(word);
this.language = "Japanese";
};
};
const japaneseWord = new JapaneseWord("犬");
const englishWord = new EnglishWord("dog");
console.log(japaneseWord.count());
console.log(japaneseWord.word);
console.log(englishWord.count());
console.log(englishWord.word);
console.log(englishWord.lookUp());
console.log(japaneseWord.lookUp());
Now it might look like our superclass constructor isn’t doing very much work. What if we defined each subclass constructor to take over all of the setup responsibilities?
class EnglishWord extends Word{
constructor(word){
this.word = word;
this.language = "English";
};
};
class JapaneseWord extends Word{
constructor(word){
this.word = word;
this.language = "Japanese";
};
};
If we do this, we’ll get an error on that third line. Why? It is a weird quirk, but in order to subclass our constructor function, we still need to call super . Otherwise, this is undefined :
class Word{
count(){
...
};
lookUp(){
...
};
};
class EnglishWord extends Word{
constructor(word){
super();
this.word = word;
this.language = "English";
};
};
class JapaneseWord extends Word{
constructor(word){
super();
this.word = word;
this.language = "Japanese";
};
};
Weirder still, even if the superclass’s constructor function is not present at all, we still have to pay it homage. We could split the responsibility like this:
class Word{
constructor(word, language){
this.word = word;
};
...
};
class EnglishWord extends Word{
constructor(word){
super(word);
this.language = "English";
};
};
class JapaneseWord extends Word{
constructor(word){
super(word);
this.language = "Japanese";
};
};
But it’s probably better just to give super all of the responsibility like this:
class Word{
constructor(word, language){
this.word = word;
this.language = language;
};
...
};
class EnglishWord extends Word{
constructor(word){
super(word, "English");
};
};
class JapaneseWord extends Word{
constructor(word){
super(word, "Japanese");
};
};
Default Parameters
You might find that, most of the time, a parameter to a function (constructor or not) tends to be the same. If that is the case, you can use default parameters like this:
class Word{
constructor(word, language="English"){
this.word = word;
this.language = language;
};
...
};
class EnglishWord extends Word{};
class JapaneseWord extends Word{
constructor(word){
super(word, "Japanese");
};
};
Calling EnglishWord ’s constructor will now just use Word ’s constructor with one argument (recall that JavaScript doesn’t mind when you call too many or too few arguments to a function). By default, the language will be English, but if a second argument is passed in, the language will be set to whatever that is instead.
Note that this does create some complexity in the function definition, as you have two potential paths instead of one. Additionally, the function calls will not necessarily all look the same.
It’s better to use default arguments for something that’s truly a default, rather than just a common case. For instance, initially marking a word in a vocabulary list as studied = false would make sense because it’s not possible for it to have been studied before it enters the system.
As for the second reason to subclass, let’s look again at our lookUp function:
class Word{
...
lookUp(){
if (this.language === "Japanese"){
return `http://jisho.org/search/${this.word}`;
}else{
return `https://en.wiktionary.org/wiki/${this.word}`;
}
};
};
if statements are not necessarily universally a bad thing, but better code will tend to avoid them through subclassing or some other polymorphic mechanism. If we delete the lookUp function from the superclass and add it to the subclasses, we’ll end up with implementations like this:
class EnglishWord extends Word{
...
lookUp(){
return `https://en.wiktionary.org/wiki/${this.word}`;
};
};
class JapaneseWord extends Word{
...
lookUp(){
return `http://jisho.org/search/${this.word}`;
};
};
This works great, and we have two tiny functions (three lines each) instead of one small function (five lines). Overall, we gained a line, but both functions are, independently, simpler to test. Better still, we only have one code path for each of them. This may seem subtle, but it means that should either branch grow in complexity—for example, switching dictionaries for different kinds of words (within a language)—the complexity will grow in a smaller context. if statements tend to lead to more if statements. Avoiding them helps to keep code bulk down, and subclassing helps to eliminate them.
By the way, notice that if we only had a Word class and no subclasses, two things would be true with our given tools: the conditional check from before would be our only option, and we wouldn’t be able to use instanceof for that check even if we wanted to.
Subclassing? Just to avoid a conditional?
You may be skeptical of subclassing being the best way to avoid conditionals. Sometimes you’ll prefer a simple conditional to subclassing. Other times, you may want to skip both the subclassing and the conditional altogether (see “Strategy” ).
There are many ways to avoid conditionals, but simplifying functions to not ask “what am I?”–type questions is key. This is sometimes called “tell, don’t ask.”
You may find that the lookup URL itself is valuable. As with the language, there are a few options here. You might change the superclass’s implementation of lookUp and just add to the subclasses’ constructors:
class Word{
lookUp(){
return this.lookUpUrl + this.word;
};
...
};
class EnglishWord extends Word{
constructor(word){
super(word, "English");
this.lookUpUrl = 'https://en.wiktionary.org/wiki/';
};
};
class JapaneseWord extends Word{
constructor(word){
super(word, "Japanese");
this.lookUpUrl = 'http://jisho.org/search/';
};
};
Additionally, you could, as we did with language , add another parameter ( lookUpUrl ) to the superclass’s constructor:
class Word{
constructor(word, language, lookUpUrl){
this.word = word;
this.language = language;
this.lookUpUrl = lookUpUrl;
};
...
};
class EnglishWord extends Word{
constructor(word){
super(word, 'English', 'https://en.wiktionary.org/wiki/');
};
};
class JapaneseWord extends Word{
constructor(word){
super(word, 'Japanese', 'http://jisho.org/search/');
};
};
My take on this is to either make the superclass do as much as possible, or as little as possible. Having the subclasses simply delegate to the superclass is fairly clean. Having the subclasses each handle as much as possible themselves (and potentially, not even have a constructor superclass) is also fairly clean. Mixing the two together, creating too much variation in the constructors of sibling classes (like EnglishWord and JapaneseWord ), having default parameters, or relying on deeper hierarchies (e.g., super ’s super ’s super ’s constructor) can all make things more confusing.
Before we move on, let’s develop some assumptions through tests. If you haven’t installed wish and deep-equal, do that now with:
npm install wish
npm install deep-equal
As for our tests, we’ll use the following:
const wish = require('wish');
const deepEqual = require('deep-equal')
// interfaces tests
wish(japaneseWord.word === "犬");
wish(japaneseWord.lookUp() === "http://jisho.org/search/犬");
wish(japaneseWord.count() === 1);
wish(englishWord.word === "dog");
wish(englishWord.lookUp() === "https://en.wiktionary.org/wiki/dog");
wish(englishWord.count() === 3);
// internals tests
wish(typeof japaneseWord === 'object');
wish(typeof JapaneseWord === 'function');
wish(japaneseWord instanceof JapaneseWord);
wish(japaneseWord instanceof Word);
wish(!(JapaneseWord instanceof Word));
wish(japaneseWord.constructor === JapaneseWord);
wish(Object.getPrototypeOf(JapaneseWord) === Word);
// sketchy bits
wish(deepEqual(Object.getPrototypeOf(japaneseWord), {}));
console.log(Object.getPrototypeOf(japaneseWord));
// reports JapaneseWord {}
The interface tests may not be terribly surprising. However, with our hierarchy variants that follow, these are the ones we’ll really care about preserving.
The internals tests are less straightforward. typeof only manages to tell us that japaneseWord is an object and JapaneseWord is a function. The best information here is probably that japaneseWord is an instance of both JapaneseWord and Word . By contrast, JapaneseWord is a class, so it’s not an instance of Word .
In the next two lines, we can see that the constructor for japaneseWord (the object) is JapaneseWord (the class) and that the prototype of JapaneseWord (the class) is Word (the class).
From there, things get a bit sketchy. The prototype of japaneseWord evaluates to an empty object, but if you log it, you’ll get a bit more info: JapaneseWord {} .
If you want to go deeper than this on prototypes, you should know a few things:
-
There’s a “nonstandard” yet popular alternative to
Object.getPrototypeOf( _thing_ ), which you use like this:_thing_ .__proto__. -
Object.getPrototypeOfhas the aliasReflect.getPrototypeOf. -
There’s another prototype inspection attribute that you can use like this:
thing.prototype. It’s super unreliable. -
Partly because there’s so much nonsense and inconsistency around prototypes, when people talk about the “real, true, deep-down” prototype of something, they’ll use syntax like
[[Prototype]]to indicate they mean the real prototype, as opposed to the five ways of actually interrogating an object.
There are some subtle and nuanced opinions concerning prototypes, but for the sake of refactoring our example, we’ll only care that the interface is preserved. For a more sympathetic and detailed exploration of prototypes in JavaScript, I’d recommend reading this & Object Prototypes , from the “You Don’t Know JS” series.
Let’s Wreck Our Hierarchy
Now that we have a nice hierarchy set up, let’s break it down, exploring these options:
- Constructor functions
- Object literals
- Factory functions
Constructor Functions
We’ve been through the noninheritance aspects of this in previous chapters, but here is how we would write the constructor function version of our class-based code from the last section:
function Word(word, language, lookUpUrl){
this.word = word;
this.language = language;
this.lookUpUrl = lookUpUrl;
this.count = function(){
return this.word.length;
};
this.lookUp = function(){
return this.lookUpUrl + this.word;
};
};
function EnglishWord(word){
Word.call(this, word, "English", 'https://en.wiktionary.org/wiki/');
};
function JapaneseWord(word){
Word.call(this, word, "Japanese", 'http://jisho.org/search/');
};
JapaneseWord.prototype = Object.create(Word.prototype);
JapaneseWord.prototype.constructor = JapaneseWord;
EnglishWord.prototype = Object.create(Word.prototype);
EnglishWord.prototype.constructor = EnglishWord;
Note that instead of relying on the constructor so heavily, we could have also let the subclass-like constructor functions do more work, as in the following:
function Word(){
this.count = function(){
return this.word.length;
};
this.lookUp = function(){
return this.lookUpUrl + this.word;
};
};
function EnglishWord(word){
Word.call(this);
this.word = word;
this.language = "English";
this.lookUpUrl = 'https://en.wiktionary.org/wiki/';
};
function JapaneseWord(word){
Word.call(this);
this.word = word;
this.language = "Japanese";
this.lookUpUrl = 'http://jisho.org/search/';
};
JapaneseWord.prototype = Object.create(Word.prototype);
JapaneseWord.prototype.constructor = JapaneseWord;
EnglishWord.prototype = Object.create(Word.prototype);
EnglishWord.prototype.constructor = EnglishWord;
This should all look fairly familiar, except for the last four lines. If we had tests in place, all of our tests and logging statements using the interfaces we’ve dealt with would pass fine without these lines. However, they are important for establishing the object hierarchy. If we don’t assign the prototype, then any changes we make to Word.prototype will not update its subclass-like objects. For example:
// with the last 4 lines from the previous snippet removed
Word.prototype.reportLanguage = function(){
return `The language is: ${this.language}`;
};
const japaneseWord = new JapaneseWord("犬");
console.log(japaneseWord.reportLanguage());
This will result in an error, because japaneseWord doesn’t know about its ancestry. Adding just the first line would fix this:
JapaneseWord.prototype = Object.create(Word.prototype);
Even without these lines, all of our original linkages to properties are still okay. In other words, our interface tests will still pass when the code is like this:
function Word(word, language, lookUpUrl){
this.word = word;
this.language = language;
this.lookUpUrl = lookUpUrl;
this.count = function(){
return this.word.length;
};
this.lookUp = function(){
return this.lookUpUrl + this.word;
};
};
function EnglishWord(word){
Word.call(this, word, "English", 'https://en.wiktionary.org/wiki/');
};
function JapaneseWord(word){
Word.call(this, word, "Japanese", 'http://jisho.org/search/');
};
// JapaneseWord.prototype = Object.create(Word.prototype);
// JapaneseWord.prototype.constructor = JapaneseWord;
// EnglishWord.prototype = Object.create(Word.prototype);
// EnglishWord.prototype.constructor = EnglishWord;
// Word.prototype.reportLanguage = function(){
// return `The language is: ${this.language}`;
// };
const japaneseWord = new JapaneseWord("犬");
// console.log(japaneseWord.reportLanguage());
const englishWord = new EnglishWord("dog");
const wish = require('wish');
const deepEqual = require('deep-equal')
// interfaces tests
wish(japaneseWord.word === "犬");
wish(japaneseWord.lookUp() === "http://jisho.org/search/犬");
wish(japaneseWord.count() === 1);
wish(englishWord.word === "dog");
wish(englishWord.lookUp() === "https://en.wiktionary.org/wiki/dog");
wish(englishWord.count() === 3);
Note that the same goes for the case of leaving more to the subclasses .
However, two of our internal tests will fail if we omit manually linking the prototype and constructor via:
JapaneseWord.prototype = Object.create(Word.prototype);
JapaneseWord.prototype.constructor = JapaneseWord;
Namely, these two tests:
wish(japaneseWord instanceof Word);
wish(Object.getPrototypeOf(JapaneseWord) === Word);
With just the first line in place:
JapaneseWord.prototype = Object.create(Word.prototype);
// JapaneseWord.prototype.constructor = JapaneseWord;
these tests will fail:
wish(japaneseWord.constructor === JapaneseWord);
wish(Object.getPrototypeOf(JapaneseWord) === Word);
And even with manually establishing both the prototype and constructor, our test from the sketchy bits will fail:
// sketchy bits
wish(deepEqual(Object.getPrototypeOf(japaneseWord), {}));
console.log(Object.getPrototypeOf(japaneseWord));
// prints JapaneseWord { constructor: [Function: JapaneseWord] }
as well as this one:
wish(Object.getPrototypeOf(JapaneseWord) === Word);
The same is true for our variant of the hierarchy that put more logic into the subclasses.
Which JavaScript Is Better?
In JavaScript, any time you want to know what an object is, know what is inside of it, know how it came to be, loop through it, or create a new one based on it, you have a lot of bad options.
My general recommendation is to stick to recent sources. You’ll see these lean toward two types of people: spec-friendly and puristic. If you follow spec-friendly people, you’ll have decent references for APIs, and you’ll see many critiques and questions around the same problems you’re having. Following the purists also has value, because they do the most questioning, push specs to improve, and spend a lot of time endorsing approaches that work well but might not be as popular. You can learn a lot from purists.
As far as inheritance, there has always been a group desperately pushing for OOP, as well as a group embracing the “true” nature of JavaScript. As of this writing, it seems that both of these groups are somehow paradoxically winning. While that’s great, it also adds an extra layer of confusion, especially when you factor in how both approaches may change year by year.
Object Literals
Next, we’ll turn to another approach we’ve used before: object literals. Let’s start with our superclass, which in this style is instead called the delegate prototype . It’s just an object:
const word = {
count(){
return this.word.length;
},
lookUp(){
return this.lookUpUrl + this.word;
}
};
So how do we inherit from it? Here is where we get stuck. Should we rely on constructor functions for the subclasses?
We don’t have to. Here is the simplest approach:
const englishWord = Object.create(word);
englishWord.word = 'dog';
englishWord.language = 'English';
englishWord.lookUpUrl = 'https://en.wiktionary.org/wiki/';
const japaneseWord = Object.create(word);
japaneseWord.word = '犬';
japaneseWord.language = 'Japanese';
japaneseWord.lookUpUrl = 'http://jisho.org/search/';
That seems a little clunky, though. We create a copy of the word object with Object.create , but then we have to assign all of our new properties in an awkward way.
Let’s try using ES2015’s Object.assign :
const englishWord = Object.assign(Object.create(word),
{word: 'dog',
language: 'English',
lookUpUrl: 'https://en.wiktionary.org/wiki/'});
const japaneseWord = Object.assign(Object.create(word),
{word: '犬',
language: 'japanese',
lookUpUrl: 'http://jisho.org/search/'});
That’s a little better because now we have one simple statement that combines objects, rather than updating them. Changing values of variables (even members of arrays and objects) is problematic, as we saw earlier, so this approach is preferable. By the way, that is also why we’re using Object.create(word) instead of just word as the first argument. The first parameter of Object.assign is actually intended to be the “target” object. If we just put word in there, it would clobber our original, rather than giving us a fresh copy to augment.
This will pass all of our interface tests, but only one of the internal tests:
// interface tests
wish(japaneseWord.word === "犬");
wish(japaneseWord.lookUp() === "http://jisho.org/search/犬");
wish(japaneseWord.count() === 1);
wish(englishWord.word === "dog");
wish(englishWord.lookUp() === "https://en.wiktionary.org/wiki/dog");
wish(englishWord.count() === 3);
// internal tests
wish(typeof japaneseWord === 'object');
console.log(Object.getPrototypeOf(japaneseWord));
// prints { count: [Function: count], lookUp: [Function: lookUp] }
We can also see that the value of japaneseWord ’s prototype is different now.
Factory Functions
The object literal option might seem pretty good as far as simplicity goes, but if we’re creating a lot of words, it might be clunky compared to using the new keyword with either class or a constructor function. We’ll explore one more alternative now.
We can use factory functions like this:
const word = {
count(){
return this.word.length;
},
lookUp(){
return this.lookUpUrl + this.word;
}
}
const englishWordFactory = (theWord) => {
return Object.assign(Object.create(word),
{word: theWord,
language: 'English',
lookUpUrl: 'https://en.wiktionary.org/wiki/'})
};
const japaneseWordFactory = (theWord) => {
return Object.assign(Object.create(word),
{word: theWord,
language: 'Japanese',
lookUpUrl: 'http://jisho.org/search/'})
};
const englishWord = englishWordFactory('dog');
const japaneseWord = japaneseWordFactory('犬');
// interfaces tests
wish(japaneseWord.word === "犬");
wish(japaneseWord.lookUp() === "http://jisho.org/search/犬");
wish(japaneseWord.count() === 1);
wish(englishWord.word === "dog");
wish(englishWord.lookUp() === "https://en.wiktionary.org/wiki/dog");
wish(englishWord.count() === 3);
Revisiting our entire reason for subclassing to begin with, we had two main purposes. First, we didn’t want to have to repeat code. Second, we wanted to get rid of the if statement. This accomplishes both of those goals. Plus, our interface tests are still passing.
So what’s the downside?
When we sever the link to some prototype (either through constructor functions or classes), we lose the ability to add attributes to many objects at once. With a class or constructor function, we can do this:
const japaneseWord = new JapaneseWord("犬"); // old code
// new code
Word.prototype.reportLanguage = function(){
return `The language is: ${this.language}`;
}
console.log(japaneseWord.reportLanguage());
We can do this even after we create the individual words. With object literals created directly or through factory functions, the objects are unavailable for these kinds of late extensions because they have no prototype chain. Note that this ability to track prototypes broke when we started using factory functions, not as a part of us using Object.create or Object.assign .
If we want that mechanism with objects that lack a prototype, we can add the prototype directly:
japaneseWord.prototype = word;
englishWord.prototype = word;
word.reportLanguage = function(){
return `The language is: ${this.language}`;
};
console.log(japaneseWord.reportLanguage());
console.log(englishWord.reportLanguage());
But for many objects, that would get tedious. Instead, we can do this with factory functions, like this:
const wordFactory = function(){
return {count(){
return this.word.length;
},
lookUp(){
return this.lookUpUrl + this.word;
}
};
};
const englishWordFactory = (theWord) => {
let copy = Object.assign(wordFactory(),
{word: theWord,
language: 'English',
lookUpUrl: 'https://en.wiktionary.org/wiki/'})
return Object.setPrototypeOf(copy, wordFactory);
};
const japaneseWordFactory = (theWord) =>{
let copy = Object.assign(wordFactory(),
{word: theWord,
language: 'Japanese',
lookUpUrl: 'http://jisho.org/search/'})
return Object.setPrototypeOf(copy, wordFactory);
};
const englishWord = englishWordFactory('dog');
const japaneseWord = japaneseWordFactory('犬');
wordFactory.reportLanguage = function(){
return `The language is: ${this.language}`;
};
console.log(japaneseWord.reportLanguage());
console.log(englishWord.reportLanguage());
It’s not strictly necessary to use a factory function for word , but this does avoid the extra step of creating a prototype (and possibly an arbitrary one) for it. Although it might seem like a hassle to manually set the prototype inside of the specific language factory functions, the alternative of manually setting them for each instance of a word would be worse if there are too many objects.
Evaluating Your Options for Hierarchies
To wrap up this section, recall that we looked at four ways to build a hierarchy:
- Classes
- Constructor functions
- Object literals
- Factory functions
Which one you choose in a given situation is up to you. Constructor functions are probably the worst option. Because they have been a perennial attempt at classes, many variants exist, and it is hard to find great documentation on them (a web search will show you ways to do them from five, six, and seven years ago—all different). If you’re considering them, just go for classes instead.
Factory functions give you a bit more control (including possibilities for establishing a prototype chain) as compared with object literals. But for simple cases, object literals are easier to work with.
Your team or codebase (including libraries you use) might be dedicated to certain methods of establishing a hierarchy. In those cases, sticking to what’s there is a decent option. You could encounter two pathological approaches, however. The first is an overreliance on manipulating and inspecting prototype, constructor, and associated utilities. For that, the remedy is to keep things superficial as much as you can. Keep testing at an interface level and focus your concerns there.
The rest of this chapter is dedicated to handling the second case: an overcommitment to hierarchies and OOP.
Inheritance and Architecture
So far, we’ve seen a few different patterns for copying data, ranging from the classiest (pseudo-) classical to the factory function that happily ignores most of the ideas around prototypes, constructors, and any other lines we’d need to draw from box to box in a UML diagram.
To recap, we know that we can make solitary objects using:
- Object literals
-
Classes (uses
new) -
Constructor functions (uses
new) - Factory functions (just returns an object)
-
Object.assignandObject.create - Libraries (like mori and Immutable.js)
Additionally, when it’s preferable to objects, we can make more specific containers as we need them, such as:
-
Set -
Map -
Array -
String -
Function - Other JavaScript types
It’s already a lot of options, but in order to round out the discussion, let’s address architectural concerns a bit more deeply, centered on answering the following questions :
- Why do some people hate classes?
- What about multiple inheritance?
- Which interfaces do you want?
Why Do Some People Hate Classes?
The first argument that some people latch onto is that new , this , super , and anything else having to do with classical OOP style detracts from their preferred mechanism of sharing data and behavior between JavaScript objects (hurting the purity and making things confusing)—but some of these criticisms are of object-oriented programming itself. They argue that it promotes bad practices like tight coupling of components, and encourages deep hierarchies and mutable state.
The class keyword is a hard blow to those who have been advocates for avoiding class-based OOP in JavaScript for a long time.
On the pro side of things, people have always struggled awkwardly to force JavaScript to behave this way. If it is what Douglas Crockford might call a “footgun,” then at the very least, condoning and standardizing the “footwounds” will make problems easier to search for and fix. There’s some degree of herd immunity if we’re all suffering from the same disease.
Also on the pro side, as features grow around classes, richer APIs become available for reflection and inspecting your code. For example, error messages can be more detailed by default.
Additionally, having a sanctioned standard for something makes it easier to learn once (adapting with the spec as necessary), rather than chasing the latest and greatest way to avoid mostly benign “syntactic sugar” for constructor functions.
The criticisms of classical OOP itself should be taken very seriously, however. A deeply nested hierarchy will be difficult to debug and maintain. Critics are not wrong to say that the extends keyword encourages a deep hierarchy (e.g., class Dog extends Pet extends Animal extends Organism ), but it does not necessarily demand it. They’re also not wrong to feel that parent/child classes tend to be tightly coupled.
What About Multiple Inheritance?
When people discuss multiple inheritance, they mean a child class inheriting from multiple parents. If we had a clean solution for this in JavaScript, it would probably mean allowing for extends to take multiple base classes as parents.
Although this type of mechanism is supported in some languages (Python, for example), it can create some confusion. If class A gets all its properties from classes B and C, how does it resolve conflicts when a property exists in both parents? It depends on the language.
If JavaScript had a class-based mechanism for multiple inheritance, it might look something like this:
class Barky{
bark(){ console.log('woof woof')};
};
class Bitey{
bark(){ console.log('grrr')};
bite(){ console.log('real bite')};
};
class Animal{
beFluffy(){ console.log('fluffy')};
bite(){ console.log('normal bite')};
};
// this is not possible:
class Dog extends (Animal, Barky, Bitey) { };
dog = new Dog;
dog.bite();
dog.beFluffy(); // this won't work
But it doesn’t. Dog will bite like a Bitey but has no idea how to be fluffy like an Animal . This isn’t multiple inheritance. Dog extends Bitey . It’s as simple as that. This is not a mechanism for multiple inheritance at all. Rather, (Animal, Barky, Bitey) just evaluates to Bitey . Check out the following:
// try this in the console:
(1, 4, 3, 7);
What do you expect this to evaluate to? Well, the answer is 7 . In some languages this expression would be an array or list literal. In others it would throw an error. In JavaScript, we get this questionable behavior of returning the last value inside the parentheses. This is what happened with our earlier attempt at multiple inheritance. This weird mechanism does not make class-based multiple inheritance possible. Dog extends Bitey , and Bitey alone. End of story.
JavaScript doesn’t have a class-based way to do multiple inheritance. For that you need some other approach. Other languages would term this a module , interface , or mixin .
What does that look like in JavaScript? Here’s one option that we’ve seen earlier in the chapter:
const barky = {
bark(){ console.log('woof woof')}
};
const bitey = {
bark(){ console.log('grrr')},
bite(){ console.log('real bite')}
};
const animal = {
beFluffy(){ console.log('fluffy')},
bite(){ console.log('normal bite')}
};
const myPet = Object.assign(Object.create(animal), barky, bitey);
myPet.beFluffy();
myPet.bark();
myPet.bite();
This will give us access to all three functions ( bark , bite , and beFluffy ). But if we dig a little deeper, we’ll see that this is not as simple as we might expect:
console.log(myPet);
{ bark: [Function: bark], bite: [Function: bite] }
console.log(Object.getPrototypeOf(myPet));
{ beFluffy: [Function: beFluffy], bite: [Function: bite] }
Our myPet object is actually relying on its prototype, the animal , for the beFluffy function. These are linked, so if we alter our beFluffy function on animal , it will update on myPet as well:
animal.beFluffy = function(){ console.log('not fluffy')}
myPet.beFluffy();
// prints "not fluffy"
We can even add new attributes to that animal to make changes to myPet on the fly:
animal.hasBankAccount = false;
console.log(myPet.hasBankAccount); // prints false
What if we try to augment the bite function?
bitey.bite = function(){
console.log("don't bite");
}
myPet.bite();
// prints "real bite"
There are two implications here. First, the bite function is attached directly to myPet from bitey . Even though myPet ’s prototype ( animal ) also has a bite function, it is overruled by the function directly attached to myPet that comes from bitey . Second, it is an actual copy. There is no linkage between bitey and myPet .
As far as our last function, bark , does myPet inherit this from bitey or barky ?
Let’s look again at how we created myPet :
const myPet = Object.assign(Object.create(animal), barky, bitey);
It turns out t hat, as parameters to Object.assign , the properties of objects to the right will overrule those to the left:
myPet.bark();
// prints "grrr"
bitey ’s bark beats barky ’s bark because bitey was last.
Is-A Versus Is-Just-A Relationships
With simple, one-parent inheritance, it is generally obvious when we intend to say that something is a subtype of something else (for example, a Person is a subtype of Organism ).
But what if a Person is also a subtype of DatabaseRecord or (shudder) Resource ?
In those cases, our model of a person is not “just” an organism, so multiple inheritance makes more sense. We just attach relevant behaviors.
It isn’t always easy to guess how a program will evolve, and inheritance hierarchies tend to be inflexible. If you want some inspiration for other ways to model object relationships, we’ll cover has-a later in this chapter, but you might also want to investigate database normalization, as well as entity-component systems, which tend to be used heavily in game development.
Which Interfaces Do You Want?
There’s more to the story here. Although we showed earlier that a factory function can sever the prototypal link in the Object.create pattern, there is another option. Before, we used this:
const myPet = Object.assign(Object.create(animal), barky, bitey);
That creates a prototypal link between myPet and animal . This can be useful because we can add functionality to animal and have it inherited by myPet (as well as other objects that were created through a similar mechanism).
But if we want a new object with the existing behavior, but without the baggage of a prototype, we could do this instead:
const myPet = Object.assign({}, animal, barky, bitey);
Now animal acts just like barky and bitey . We can add properties to them , but myPet is unaffected:
animal.hasBankAccount = false;
console.log(myPet.hasBankAccount); // prints undefined
Another way to look at this is that myPet ’s prototype is now {} , rather than animal :
console.log(Object.getPrototypeOf(myPet));
// prints "{}"
Also notice that beFluffy (the function inherited from animal ) is defined directly on myPet :
console.log(myPet);
// prints
{ beFluffy: [Function: beFluffy],
bite: [Function: bite],
bark: [Function: bark] }
Most of the time, your primary concern will just be whether or not an object has a particular function or other property attached to it. In other words, “Can I call this function on this object?” is a question that is absolutely fundamental in defining your API. As such, it is worth documenting, testing, manipulating, and refactoring.
But there is another broad and confusing set of interfaces underneath every JavaScript program. Do you want to use Object.getPrototypeOf ? What about Object.is ? .__proto__ ? .prototype ? .constructor ? .keys ? Reflect.ownKeys ? Reflect.has ? typeof ? instanceof ?
Let’s call this “JavaScript’s deep, dark underbelly.”
Are you confident that these all behave as you expect? Are the desired properties enumerable when you want to loop through an object? When you create a new object, are you exposing either your new or old objects to side effects?
You’re likely to encounter projects that favor one style or another. You might even see a codebase with a dual personality, perhaps with half of it in a classical style and the other half using factory functions. Whatever your preferred style is, rewriting the “wrong” style is likely to be painful, and possibly confusing and insulting to other team members.
Although it is best to promote confidence early in a project by having answered Chapter 2 ’s question of “Which JavaScript are you using?” with a style guide (and better yet, a linter that runs in your editor to enforce this automatically), you won’t always be so lucky.
On a project that lacks opinions on a given style, and hurts confidence in that second interface (that of inspection and reflection), what should you do?
If you are not confident in a piece of code, write a test. For example, for this code:
const myPet = Object.assign({}, animal, barky, bitey);
use characterization tests to develop confidence in things like Object.keys(myPet) , myPet.__proto__ , Object.getOwnPropertyNames(myPet) , Object.getPrototypeOf(myPet) , and any other members of this deeper interface of JavaScript. As we practiced in Chapter 4 , use wish(value, true) or assert(value === null) . Then use the output of that characterization test to fill in the test: wish(value === valueFromOutput) or assert(value === valueFromOutput) .
Aren’t these values already tested within JavaScript browser implementations? Yes, absolutely; they already have tests covering them. Are they “implementation details,” which many argue against writing tests for? Definitely. Will these tests be brittle if you change from classes to factory functions or from factory functions to classes? Yes.
But if they cause confusion in your code, should you test these functions in spite of that?
Without a doubt. It does not matter how much a piece of code is external to your codebase or how much of an implementation detail it is. You can use tests to clear up your confusion (you won’t be the only one on the team who’s confused anyway) and have more confidence in your code. Additionally, you may be relying on JavaScript’s deep, dark underbelly more than you think. For instance, what seems like it should be a cosmetic change might be affecting a property’s enumerability or an object’s prototype .
If letting your code break in tests instead of in production is your goal, creating characterization tests like these can add a layer of confidence that rigidly only testing the public interface may not give you. Additionally, if you’re moving between factory functions, constructor functions, object literals, and classes, it’s not a bad idea to have a sense of what is changing, even at a deeper level than the interface you directly care about.
Has-A Relationships
So far in this chapter, we’ve been looking at multiple objects from the perspective of “is-a” (or “is a subtype of”) relationships. For simple inheritance, an EnglishWord is a Word . This is true even when dealing with mixins/multiple inheritance/modules: myPet is-a animal , but myPet is-a bitey and myPet is-a barky also.
We saw how these is-a relationships may imply a prototypal link between child and parent, but according to stylistic choices within JavaScript, that link may be severed despite any adopted similarities of interface between the objects. We also saw how establishing or severing that link can impact many interfaces within JavaScript’s deep, dark underbelly.
What we haven’t talked about is that composing objects does not necessarily imply inheriting properties .
Is a HorseWithABriefCase a subtype of Horse ? That sounds awfully specific. Maybe it’s a subtype of HorseWithObject , or should it be a subtype of BusinessHorse ? We could put all of our horses into a hierarchy of some form, but then we’ll need an object (and/or class) that ends up describing every attribute, lest our SickHorse cannot get the antibiotics she needs because DoctorHorseWithoutAnyMedicine is perfectly unhelpful in that scenario.
Obviously, we already have a way to deal with this by storing properties (of arbitrary types) on objects. In Chapters 6 and 7 , we dealt with a classifier that has-a songList . In our Object.create / Object.assign mixin-based inheritance from earlier in the chapter, we were copying properties from one object to another. By contrast, in our classifier , we had to specifically drill down into the songList via classifier.songList.addSong (until we wrote the delegate function to drill down for us, allowing us to instead write classifier.addSong ).
As for our horses, we could start by doing something like this:
const horse = {
inventory: ["briefcase"],
profession: "hippo jockey",
healthy: true
}
As our program grew in complexity, we might need a lot of horses, so we’d use a class, a constructor function, Object.create , or a factory function to help us get more horses. If we needed to add behaviors to the horses, we would add functions as properties .
If inventory or briefcase or other properties needed to be more complicated, we’d spin them out as their own objects (as we did with songList in Chapter 7 ). If they needed some behavior to be attached, we’d add functions to those objects.
The reason for glossing over a general approach for how to grow JavaScript objects without a hierarchy is that it is not usually how things go wrong in JavaScript programs. Although building a complex, deep, or complicated hierarchy of JavaScript classes/objects is possible and may become more of a widespread problem as OOP with classes becomes more popular, as of this writing the worst JavaScript codebases are much more likely to suffer from a lack of structure than from too much structure of the wrong kind.
That said, next we’ll address a few structural mistakes that you might see from time to time.
Inheritance Antipatterns
Here we’ll look at two issues that can come up when the wrong kind of structure is in place. Here are the antipatterns we’ll address:
- Hyperextension (hierarchy is too deep)
- Goat and cabbage raised by a wolf (parent and children have nothing in common )
In both cases, the motivation likely comes from a good place. Programmers don’t like to just copy and paste code with minor variations. This is called “cargo cult” coding, and is a brand new programmer’s best friend.
To avoid that, you create new aspects of a hierarchy instead of extracting functions and subobjects that could be shared or held independently.
Hyperextension
Here we have an example of a hierarchy that is too deep. SpecificClientReport inherits from ClientReport , which inherits from GenericReport , which inherits from Report :
class Report{
constructor(params){
this.params = params;
}
printReport(params){
return params;
}
}
class GenericReport extends Report{
constructor(params){
super(params);
this.params = params;
}
printReport(params){
return super.printReport(Object.assign(this.params, params));
}
}
class ClientReport extends GenericReport{
constructor(params){
super(params);
this.params = params;
}
printReport(params){
return super.printReport(Object.assign(this.params, params));
}
}
class SpecificClientReport extends ClientReport{
constructor(params){
super(params);
this.params = params;
}
printReport(params){
return super.printReport(Object.assign(this.params, params));
}
}
const report =
new SpecificClientReport({whatever: 'we want', to: 'add'});
console.log(report.printReport({extra: 'params'}));
If there were ever a good reason not to just pass the word params , object , or options around, here it is. Imagine this code, but with more functions, and alterations of params and this.params all along the way.
If we had function calls to other members of this hierarchy, we would address them too, but here we’ll just focus on SpecificClientReport . First, we need a test instead of a logging statement. Create a characterization test by adding these lines to the bottom :
const wish = require('wish');
const deepEqual = require('deep-equal');
wish(report.printReport({extra: 'params'}), true);
We run it and get an error:
WishCharacterization: report.printReport({extra: 'params'})
evaluated to {"whatever":"we want","to":"add","extra":"params"}
That object is exactly what we need to replace our characterization test:
wish(deepEqual(report.printReport({extra: 'params'}),
{whatever:"we want", to:"add", extra:"params"}));
And our test passes. Now we can safely refactor.
There are two approaches we could take. First, we could assume that there’s nothing special about our SpecificClientReport and try this instead:
const report = new Report({whatever: 'we want', to: 'add'});
wish(deepEqual(report.printReport({extra: 'params'}),
{whatever:"we want", to:"add", extra:"params"}));
Note that we’re just changing the report variable here (and in the next snippet). The test is the same. We get an error, so we could try moving down one level:
const report = new GenericReport({whatever: 'we want', to: 'add'});
wish(deepEqual(report.printReport({extra: 'params'}),
{whatever:"we want", to:"add", extra:"params"}))
This works fine. That means (assuming there are no other places using them) we can delete SpecificClientReport and ClientReport . If they both have other places using them, we should see if we could move those places up in the hierarchy to try to prune any leaves we can.
The second way to handle this is to see if we can inline the superclass’s functionality. Because SpecificClientReport and GenericReport behave the same way (according to our tests), it’s fine to start where we just left off. If the last approach was difficult for your codebase, you might start with this technique instead (before climbing the superclasses).
In any event, we’re left with this:
class Report{
constructor(params){
this.params = params;
}
printReport(params){
return params;
}
}
class GenericReport extends Report{
constructor(params){
super(params);
this.params = params;
}
printReport(params){
return super.printReport(Object.assign(this.params, params));
}
}
const wish = require('wish');
const deepEqual = require('deep-equal');
report = new GenericReport({whatever: 'we want', to: 'add'});
wish(deepEqual(report.printReport({extra: 'params'}),
{whatever:"we want", to:"add", extra:"params"}));
To get a little clarity, we can start by removing the constructor function from GenericReport (assuming that we are the only consumer), as it is redundant with what happens in super . As for the printReport function, all super does is return what it is given (the params , not the this.params ). That means we don’t have to call super at all, making our new GenericReport look like this:
class GenericReport extends Report{
printReport(params){
return Object.assign(this.params, params);
};
};
The test passes. We’re almost ready to free this child class. However, if we remove extends Report now, we’ll get an error, because this.params was never assigned. That means we need our constructor back first. After that, we’re free to remove the link to the parent:
class GenericReport{
constructor(params){
this.params = params;
};
printReport(params){
return Object.assign(this.params, params);
};
};
And everything works. If GenericReport was the only thing using Report , we could remove it ( Report ) now. After that, the ugliest things in here are the nonspecific names: params should be something more specific (see Chapter 6 ), and GenericReport could possibly be called Report now.
If you decide to prune a hierarchy like this, it is crucial to have version control and tests in place that can check all of the consumers (object makers/function callers) of the classes along the hierarchy.
It’s unlikely to go as smoothly as this. Ultimately, the goal is to carve off independent leaves and extract shared functions when you can. Don’t try to “refactor” a complex hierarchy like this (but with many more side effects, attributes, and functions) all at once, especially not without tests in place.
Goat and Cabbage Raised by a Wolf
In this case, the children look nothing like the parent or each other. All the parent does is cause confusion and add a layer of indirection:
class Agent{
constructor(name, type){
this.name = 'name';
if(Math.random() > .5){
this.type = 'user';
}else{
this.type = 'project';
}
};
static makeProjectOrUser(agent){
if(agent.type === 'user'){
return Object.assign(Object.create(new User), agent);
}else{
return Object.assign(Object.create(new Project), agent);
}
};
};
class User extends Agent{
sayName(){
return `my name is ${this.name}`;
}
};
class Project extends Agent{
sayTheName(){
return `the project name is ${this.name}`;
}
};
const agent = new Agent('name');
const projectOrUser = Agent.makeProjectOrUser(agent);
For this code, imagine that this is basically as common as it gets between the two objects, and there are thousands of lines backing up the difference between them (all requiring tests and type checking, aka conditionals).
First, we need to get some characterization tests in place. Add these lines to the end:
const wish = require('wish');
if(projectOrUser.type === 'user'){
wish(projectOrUser.sayName(), true);
}else{
wish(projectOrUser.sayTheName(), true);
}
We’ll have a 50/50 chance of getting one of these:
WishCharacterization: projectOrUser.sayName() evaluated to
"my name is name"
// or
WishCharacterization: projectOrUser.sayTheName() evaluated to
"the project name is name"
Now we can just replace our characterization tests with these:
if(projectOrUser.type === 'user'){
wish(projectOrUser.sayName() === "my name is name");
}else{
wish(projectOrUser.sayTheName() === "the project name is name");
}
We will always have problems as long as the following two lines are in place:
const agent = new Agent('name');
const projectOrUser = Agent.makeProjectOrUser(agent);
Right now, these create a project or a user , based on a coin toss in the constructor. Since that is where the whole problem stems from, let’s move the coin toss into a function:
function coinToss(){
return Math.random() > .5;
};
class Agent{
constructor(name, type){
this.name = name;
if(coinToss()){
this.type = 'user';
}else{
this.type = 'project';
}
};
...
};
Next, because coinToss is always called, we can move that to our calling code, outside the constructor:
class Agent{
constructor(name, type){
this.name = name;
this.type = type;
};
};
and move our coinToss to be used before our agent is given an identity:
let agent;
if(coinToss()){
agent = new Agent('name', 'user');
}else{
agent = new Agent('name', 'project');
}
// replaces
// const agent = new Agent('name');
Now, we want to “push down” the constructor into the subtypes:
class User extends Agent{
constructor(name, type){
super();
this.name = name;
this.type = type;
};
sayName(){
return `my name is ${this.name}`;
};
}
class Project extends Agent{
constructor(name, type){
super();
this.name = name;
this.type = type;
};
sayTheName(){
return `the project name is ${this.name}`;
};
};
Annoyingly, as long as we’re extending Agent , in JavaScript we must call its constructor (with super ) in order to access this and assign properties in our subtypes. Note that we don’t care about passing arguments to super because we’re assigning the properties we need anyway.
Okay, here’s the exciting part. Now we can call those constructors directly:
let agent;
if(coinToss()){
agent = new User('name', 'user');
}else{
agent = new Project('name', 'project');
}
Now we can delete a lot of code, leaving us with just the following:
function coinToss(){
return Math.random() > .5;
};
class User{
constructor(name, type){
this.name = name;
this.type = type;
};
sayName(){
return `my name is ${this.name}`;
};
};
class Project{
constructor(name, type){
this.name = name;
this.type = type;
};
sayTheName(){
return `the project name is ${this.name}`;
};
};
let agent;
if(coinToss()){
agent = new User('name', 'user');
}else{
agent = new Project('name', 'project');
}
const wish = require('wish');
if(agent.type === 'user'){
wish(agent.sayName() === "my name is name");
}else{
wish(agent.sayTheName() === "the project name is name");
}
No more super . No more extends . Now we’re free to rename the variable agent to anything we like. You might notice another potential refactoring in unifying the interface of the functions sayName and sayTheName . By all means, go ahead, as long as it won’t tempt you to subclass these again.
If you think the coin toss to decide on a type of object is a bit far-fetched, you’re totally correct. The point is, however, that ambivalent constructors—which could be based on date, time, or any other dynamic situation— could lead to this scenario. Or such a scenario could be the result of one ambiguous object creation slowly spreading throughout the codebase. I’ve seen it happen.
Also note, as we’ve discussed before, that having our test suite rely on randomness like this is not great. Really, we’d want the following tests as well:
wish(new User('name', 'user').sayName() === "my name is name");
wish(new Project('name', 'project').sayTheName()
=== "the project name is name");
Since our coin toss is just representing some (probably very confusing) way that the objects come into being, there’s no clear way to remove that conditional. However, note that instead of passing an explicit type variable into the constructor, we could rely on the class instead:
class User{
constructor(name){
this.name = name;
};
...
class Project{
constructor(name){
this.name = name;
};
...
if(agent instanceof User){
wish(agent.sayName() === "my name is name");
}else{
wish(agent.sayTheName() === "the project name is name");
}
...
The lesson here is that if you have two classes that share some state or behavior, subclassing may not be a great way to remove duplication, and it could lead your team down a path of lots and lots of type checking. Sometimes, you just need a type attribute (we’ll look at a way to avoid a conditional check with these in Chapter 9 ). Other times, you might be able to extract the duplication into functions or another object. In any case, refactoring duplication is very easy and safe compared to dismantling a “goat and cabbage raised by a wolf” inheritance issue.
Wrapping Up
In this chapter, we looked at a few ways to build up as well as break down a hierarchy. It’s worth noting that for some people, object-oriented programming is more trouble than it’s worth. If you’re one of those people, you’ll probably like learning about functional programming in Chapter 11 . If you like OOP, the next chapter will give you a few more tools (patterns) to apply to your work.
Whatever your stance on OOP, you’re likely to see code that could benefit from the kind of organization that it provides. On the other hand, you might find that misapplied OOP itself is the cause of complexity in some codebases. In any case, none of this suggests that objects or classes are inherently bad to use.