GithubHelp home page GithubHelp logo

ryanmcdermott / clean-code-javascript Goto Github PK

View Code? Open in Web Editor NEW
89.7K 1.9K 12.0K 520 KB

:bathtub: Clean Code concepts adapted for JavaScript

License: MIT License

JavaScript 100.00%
javascript principles composition inheritance clean-code clean-architecture best-practices

clean-code-javascript's Introduction

clean-code-javascript

Table of Contents

  1. Introduction
  2. Variables
  3. Functions
  4. Objects and Data Structures
  5. Classes
  6. SOLID
  7. Testing
  8. Concurrency
  9. Error Handling
  10. Formatting
  11. Comments
  12. Translation

Introduction

Humorous image of software quality estimation as a count of how many expletives you shout when reading code

Software engineering principles, from Robert C. Martin's book Clean Code, adapted for JavaScript. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in JavaScript.

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

Our craft of software engineering is just a bit over 50 years old, and we are still learning a lot. When software architecture is as old as architecture itself, maybe then we will have harder rules to follow. For now, let these guidelines serve as a touchstone by which to assess the quality of the JavaScript code that you and your team produce.

One more thing: knowing these won't immediately make you a better software developer, and working with them for many years doesn't mean you won't make mistakes. Every piece of code starts as a first draft, like wet clay getting shaped into its final form. Finally, we chisel away the imperfections when we review it with our peers. Don't beat yourself up for first drafts that need improvement. Beat up the code instead!

Variables

Use meaningful and pronounceable variable names

Bad:

const yyyymmdstr = moment().format("YYYY/MM/DD");

Good:

const currentDate = moment().format("YYYY/MM/DD");

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:

getUserInfo();
getClientData();
getCustomerRecord();

Good:

getUser();

⬆ back to top

Use searchable names

We will read more code than we will ever write. It's important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. Tools like buddy.js and ESLint can help identify unnamed constants.

Bad:

// What the heck is 86400000 for?
setTimeout(blastOff, 86400000);

Good:

// Declare them as capitalized named constants.
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000;

setTimeout(blastOff, MILLISECONDS_PER_DAY);

⬆ back to top

Use explanatory variables

Bad:

const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
  address.match(cityZipCodeRegex)[1],
  address.match(cityZipCodeRegex)[2]
);

Good:

const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);

⬆ back to top

Avoid Mental Mapping

Explicit is better than implicit.

Bad:

const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(l => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // Wait, what is `l` for again?
  dispatch(l);
});

Good:

const locations = ["Austin", "New York", "San Francisco"];
locations.forEach(location => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  dispatch(location);
});

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in your variable name.

Bad:

const Car = {
  carMake: "Honda",
  carModel: "Accord",
  carColor: "Blue"
};

function paintCar(car, color) {
  car.carColor = color;
}

Good:

const Car = {
  make: "Honda",
  model: "Accord",
  color: "Blue"
};

function paintCar(car, color) {
  car.color = color;
}

⬆ back to top

Use default parameters instead of short circuiting or conditionals

Default parameters are often cleaner than short circuiting. Be aware that if you use them, your function will only provide default values for undefined arguments. Other "falsy" values such as '', "", false, null, 0, and NaN, will not be replaced by a default value.

Bad:

function createMicrobrewery(name) {
  const breweryName = name || "Hipster Brew Co.";
  // ...
}

Good:

function createMicrobrewery(name = "Hipster Brew Co.") {
  // ...
}

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.

One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument.

Since JavaScript allows you to make objects on the fly, without a lot of class boilerplate, you can use an object if you are finding yourself needing a lot of arguments.

To make it obvious what properties the function expects, you can use the ES2015/ES6 destructuring syntax. This has a few advantages:

  1. When someone looks at the function signature, it's immediately clear what properties are being used.
  2. It can be used to simulate named parameters.
  3. Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned.
  4. Linters can warn you about unused properties, which would be impossible without destructuring.

Bad:

function createMenu(title, body, buttonText, cancellable) {
  // ...
}

createMenu("Foo", "Bar", "Baz", true);

Good:

function createMenu({ title, body, buttonText, cancellable }) {
  // ...
}

createMenu({
  title: "Foo",
  body: "Bar",
  buttonText: "Baz",
  cancellable: true
});

⬆ back to top

Functions should do one thing

This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers.

Bad:

function emailClients(clients) {
  clients.forEach(client => {
    const clientRecord = database.lookup(client);
    if (clientRecord.isActive()) {
      email(client);
    }
  });
}

Good:

function emailActiveClients(clients) {
  clients.filter(isActiveClient).forEach(email);
}

function isActiveClient(client) {
  const clientRecord = database.lookup(client);
  return clientRecord.isActive();
}

⬆ back to top

Function names should say what they do

Bad:

function addToDate(date, month) {
  // ...
}

const date = new Date();

// It's hard to tell from the function name what is added
addToDate(date, 1);

Good:

function addMonthToDate(month, date) {
  // ...
}

const date = new Date();
addMonthToDate(1, date);

⬆ back to top

Functions should only be one level of abstraction

When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.

Bad:

function parseBetterJSAlternative(code) {
  const REGEXES = [
    // ...
  ];

  const statements = code.split(" ");
  const tokens = [];
  REGEXES.forEach(REGEX => {
    statements.forEach(statement => {
      // ...
    });
  });

  const ast = [];
  tokens.forEach(token => {
    // lex...
  });

  ast.forEach(node => {
    // parse...
  });
}

Good:

function parseBetterJSAlternative(code) {
  const tokens = tokenize(code);
  const syntaxTree = parse(tokens);
  syntaxTree.forEach(node => {
    // parse...
  });
}

function tokenize(code) {
  const REGEXES = [
    // ...
  ];

  const statements = code.split(" ");
  const tokens = [];
  REGEXES.forEach(REGEX => {
    statements.forEach(statement => {
      tokens.push(/* ... */);
    });
  });

  return tokens;
}

function parse(tokens) {
  const syntaxTree = [];
  tokens.forEach(token => {
    syntaxTree.push(/* ... */);
  });

  return syntaxTree;
}

⬆ back to top

Remove duplicate code

Do your absolute best to avoid duplicate code. Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.

Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc. If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them. If you only have one list, there's only one place to update!

Oftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class.

Getting the abstraction right is critical, that's why you should follow the SOLID principles laid out in the Classes section. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself updating multiple places anytime you want to change one thing.

Bad:

function showDeveloperList(developers) {
  developers.forEach(developer => {
    const expectedSalary = developer.calculateExpectedSalary();
    const experience = developer.getExperience();
    const githubLink = developer.getGithubLink();
    const data = {
      expectedSalary,
      experience,
      githubLink
    };

    render(data);
  });
}

function showManagerList(managers) {
  managers.forEach(manager => {
    const expectedSalary = manager.calculateExpectedSalary();
    const experience = manager.getExperience();
    const portfolio = manager.getMBAProjects();
    const data = {
      expectedSalary,
      experience,
      portfolio
    };

    render(data);
  });
}

Good:

function showEmployeeList(employees) {
  employees.forEach(employee => {
    const expectedSalary = employee.calculateExpectedSalary();
    const experience = employee.getExperience();

    const data = {
      expectedSalary,
      experience
    };

    switch (employee.type) {
      case "manager":
        data.portfolio = employee.getMBAProjects();
        break;
      case "developer":
        data.githubLink = employee.getGithubLink();
        break;
    }

    render(data);
  });
}

⬆ back to top

Set default objects with Object.assign

Bad:

const menuConfig = {
  title: null,
  body: "Bar",
  buttonText: null,
  cancellable: true
};

function createMenu(config) {
  config.title = config.title || "Foo";
  config.body = config.body || "Bar";
  config.buttonText = config.buttonText || "Baz";
  config.cancellable =
    config.cancellable !== undefined ? config.cancellable : true;
}

createMenu(menuConfig);

Good:

const menuConfig = {
  title: "Order",
  // User did not include 'body' key
  buttonText: "Send",
  cancellable: true
};

function createMenu(config) {
  let finalConfig = Object.assign(
    {
      title: "Foo",
      body: "Bar",
      buttonText: "Baz",
      cancellable: true
    },
    config
  );
  return finalConfig
  // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  // ...
}

createMenu(menuConfig);

⬆ back to top

Don't use flags as function parameters

Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.

Bad:

function createFile(name, temp) {
  if (temp) {
    fs.create(`./temp/${name}`);
  } else {
    fs.create(name);
  }
}

Good:

function createFile(name) {
  fs.create(name);
}

function createTempFile(name) {
  createFile(`./temp/${name}`);
}

⬆ back to top

Avoid Side Effects (part 1)

A function produces a side effect if it does anything other than take a value in and return another value or values. A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger.

Now, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file. What you want to do is to centralize where you are doing this. Don't have several functions and classes that write to a particular file. Have one service that does it. One and only one.

The main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers.

Bad:

// Global variable referenced by following function.
// If we had another function that used this name, now it'd be an array and it could break it.
let name = "Ryan McDermott";

function splitIntoFirstAndLastName() {
  name = name.split(" ");
}

splitIntoFirstAndLastName();

console.log(name); // ['Ryan', 'McDermott'];

Good:

function splitIntoFirstAndLastName(name) {
  return name.split(" ");
}

const name = "Ryan McDermott";
const newName = splitIntoFirstAndLastName(name);

console.log(name); // 'Ryan McDermott';
console.log(newName); // ['Ryan', 'McDermott'];

⬆ back to top

Avoid Side Effects (part 2)

In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so it's important to handle them carefully when they're passed as parameters to a function. A JavaScript function can change an object's properties or alter the contents of an array which could easily cause bugs elsewhere.

Suppose there's a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that same cart array will be affected by this addition. That may be great, however it could also be bad. Let's imagine a bad situation:

The user clicks the "Purchase" button which calls a purchase function that spawns a network request and sends the cart array to the server. Because of a bad network connection, the purchase function has to keep retrying the request. Now, what if in the meantime the user accidentally clicks an "Add to Cart" button on an item they don't actually want before the network request begins? If that happens and the network request begins, then that purchase function will send the accidentally added item because the cart array was modified.

A great solution would be for the addItemToCart function to always clone the cart, edit it, and return the clone. This would ensure that functions that are still using the old shopping cart wouldn't be affected by the changes.

Two caveats to mention to this approach:

  1. There might be cases where you actually want to modify the input object, but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects!

  2. Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there are great libraries that allow this kind of programming approach to be fast and not as memory intensive as it would be for you to manually clone objects and arrays.

Bad:

const addItemToCart = (cart, item) => {
  cart.push({ item, date: Date.now() });
};

Good:

const addItemToCart = (cart, item) => {
  return [...cart, { item, date: Date.now() }];
};

⬆ back to top

Don't write to global functions

Polluting globals is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to extend JavaScript's native Array method to have a diff method that could show the difference between two arrays? You could write your new function to the Array.prototype, but it could clash with another library that tried to do the same thing. What if that other library was just using diff to find the difference between the first and last elements of an array? This is why it would be much better to just use ES2015/ES6 classes and simply extend the Array global.

Bad:

Array.prototype.diff = function diff(comparisonArray) {
  const hash = new Set(comparisonArray);
  return this.filter(elem => !hash.has(elem));
};

Good:

class SuperArray extends Array {
  diff(comparisonArray) {
    const hash = new Set(comparisonArray);
    return this.filter(elem => !hash.has(elem));
  }
}

⬆ back to top

Favor functional programming over imperative programming

JavaScript isn't a functional language in the way that Haskell is, but it has a functional flavor to it. Functional languages can be cleaner and easier to test. Favor this style of programming when you can.

Bad:

const programmerOutput = [
  {
    name: "Uncle Bobby",
    linesOfCode: 500
  },
  {
    name: "Suzie Q",
    linesOfCode: 1500
  },
  {
    name: "Jimmy Gosling",
    linesOfCode: 150
  },
  {
    name: "Gracie Hopper",
    linesOfCode: 1000
  }
];

let totalOutput = 0;

for (let i = 0; i < programmerOutput.length; i++) {
  totalOutput += programmerOutput[i].linesOfCode;
}

Good:

const programmerOutput = [
  {
    name: "Uncle Bobby",
    linesOfCode: 500
  },
  {
    name: "Suzie Q",
    linesOfCode: 1500
  },
  {
    name: "Jimmy Gosling",
    linesOfCode: 150
  },
  {
    name: "Gracie Hopper",
    linesOfCode: 1000
  }
];

const totalOutput = programmerOutput.reduce(
  (totalLines, output) => totalLines + output.linesOfCode,
  0
);

⬆ back to top

Encapsulate conditionals

Bad:

if (fsm.state === "fetching" && isEmpty(listNode)) {
  // ...
}

Good:

function shouldShowSpinner(fsm, listNode) {
  return fsm.state === "fetching" && isEmpty(listNode);
}

if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
  // ...
}

⬆ back to top

Avoid negative conditionals

Bad:

function isDOMNodeNotPresent(node) {
  // ...
}

if (!isDOMNodeNotPresent(node)) {
  // ...
}

Good:

function isDOMNodePresent(node) {
  // ...
}

if (isDOMNodePresent(node)) {
  // ...
}

⬆ back to top

Avoid conditionals

This seems like an impossible task. Upon first hearing this, most people say, "how am I supposed to do anything without an if statement?" The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, "well that's great but why would I want to do that?" The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that have if statements, you are telling your user that your function does more than one thing. Remember, just do one thing.

Bad:

class Airplane {
  // ...
  getCruisingAltitude() {
    switch (this.type) {
      case "777":
        return this.getMaxAltitude() - this.getPassengerCount();
      case "Air Force One":
        return this.getMaxAltitude();
      case "Cessna":
        return this.getMaxAltitude() - this.getFuelExpenditure();
    }
  }
}

Good:

class Airplane {
  // ...
}

class Boeing777 extends Airplane {
  // ...
  getCruisingAltitude() {
    return this.getMaxAltitude() - this.getPassengerCount();
  }
}

class AirForceOne extends Airplane {
  // ...
  getCruisingAltitude() {
    return this.getMaxAltitude();
  }
}

class Cessna extends Airplane {
  // ...
  getCruisingAltitude() {
    return this.getMaxAltitude() - this.getFuelExpenditure();
  }
}

⬆ back to top

Avoid type-checking (part 1)

JavaScript is untyped, which means your functions can take any type of argument. Sometimes you are bitten by this freedom and it becomes tempting to do type-checking in your functions. There are many ways to avoid having to do this. The first thing to consider is consistent APIs.

Bad:

function travelToTexas(vehicle) {
  if (vehicle instanceof Bicycle) {
    vehicle.pedal(this.currentLocation, new Location("texas"));
  } else if (vehicle instanceof Car) {
    vehicle.drive(this.currentLocation, new Location("texas"));
  }
}

Good:

function travelToTexas(vehicle) {
  vehicle.move(this.currentLocation, new Location("texas"));
}

⬆ back to top

Avoid type-checking (part 2)

If you are working with basic primitive values like strings and integers, and you can't use polymorphism but you still feel the need to type-check, you should consider using TypeScript. It is an excellent alternative to normal JavaScript, as it provides you with static typing on top of standard JavaScript syntax. The problem with manually type-checking normal JavaScript is that doing it well requires so much extra verbiage that the faux "type-safety" you get doesn't make up for the lost readability. Keep your JavaScript clean, write good tests, and have good code reviews. Otherwise, do all of that but with TypeScript (which, like I said, is a great alternative!).

Bad:

function combine(val1, val2) {
  if (
    (typeof val1 === "number" && typeof val2 === "number") ||
    (typeof val1 === "string" && typeof val2 === "string")
  ) {
    return val1 + val2;
  }

  throw new Error("Must be of type String or Number");
}

Good:

function combine(val1, val2) {
  return val1 + val2;
}

⬆ back to top

Don't over-optimize

Modern browsers do a lot of optimization under-the-hood at runtime. A lot of times, if you are optimizing then you are just wasting your time. There are good resources for seeing where optimization is lacking. Target those in the meantime, until they are fixed if they can be.

Bad:

// On old browsers, each iteration with uncached `list.length` would be costly
// because of `list.length` recomputation. In modern browsers, this is optimized.
for (let i = 0, len = list.length; i < len; i++) {
  // ...
}

Good:

for (let i = 0; i < list.length; i++) {
  // ...
}

⬆ back to top

Remove dead code

Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. If it's not being called, get rid of it! It will still be safe in your version history if you still need it.

Bad:

function oldRequestModule(url) {
  // ...
}

function newRequestModule(url) {
  // ...
}

const req = newRequestModule;
inventoryTracker("apples", req, "www.inventory-awesome.io");

Good:

function newRequestModule(url) {
  // ...
}

const req = newRequestModule;
inventoryTracker("apples", req, "www.inventory-awesome.io");

⬆ back to top

Objects and Data Structures

Use getters and setters

Using getters and setters to access data on objects could be better than simply looking for a property on an object. "Why?" you might ask. Well, here's an unorganized list of reasons why:

  • When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
  • Makes adding validation simple when doing a set.
  • Encapsulates the internal representation.
  • Easy to add logging and error handling when getting and setting.
  • You can lazy load your object's properties, let's say getting it from a server.

Bad:

function makeBankAccount() {
  // ...

  return {
    balance: 0
    // ...
  };
}

const account = makeBankAccount();
account.balance = 100;

Good:

function makeBankAccount() {
  // this one is private
  let balance = 0;

  // a "getter", made public via the returned object below
  function getBalance() {
    return balance;
  }

  // a "setter", made public via the returned object below
  function setBalance(amount) {
    // ... validate before updating the balance
    balance = amount;
  }

  return {
    // ...
    getBalance,
    setBalance
  };
}

const account = makeBankAccount();
account.setBalance(100);

⬆ back to top

Make objects have private members

This can be accomplished through closures (for ES5 and below).

Bad:

const Employee = function(name) {
  this.name = name;
};

Employee.prototype.getName = function getName() {
  return this.name;
};

const employee = new Employee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined

Good:

function makeEmployee(name) {
  return {
    getName() {
      return name;
    }
  };
}

const employee = makeEmployee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe

⬆ back to top

Classes

Prefer ES2015/ES6 classes over ES5 plain functions

It's very difficult to get readable class inheritance, construction, and method definitions for classical ES5 classes. If you need inheritance (and be aware that you might not), then prefer ES2015/ES6 classes. However, prefer small functions over classes until you find yourself needing larger and more complex objects.

Bad:

const Animal = function(age) {
  if (!(this instanceof Animal)) {
    throw new Error("Instantiate Animal with `new`");
  }

  this.age = age;
};

Animal.prototype.move = function move() {};

const Mammal = function(age, furColor) {
  if (!(this instanceof Mammal)) {
    throw new Error("Instantiate Mammal with `new`");
  }

  Animal.call(this, age);
  this.furColor = furColor;
};

Mammal.prototype = Object.create(Animal.prototype);
Mammal.prototype.constructor = Mammal;
Mammal.prototype.liveBirth = function liveBirth() {};

const Human = function(age, furColor, languageSpoken) {
  if (!(this instanceof Human)) {
    throw new Error("Instantiate Human with `new`");
  }

  Mammal.call(this, age, furColor);
  this.languageSpoken = languageSpoken;
};

Human.prototype = Object.create(Mammal.prototype);
Human.prototype.constructor = Human;
Human.prototype.speak = function speak() {};

Good:

class Animal {
  constructor(age) {
    this.age = age;
  }

  move() {
    /* ... */
  }
}

class Mammal extends Animal {
  constructor(age, furColor) {
    super(age);
    this.furColor = furColor;
  }

  liveBirth() {
    /* ... */
  }
}

class Human extends Mammal {
  constructor(age, furColor, languageSpoken) {
    super(age, furColor);
    this.languageSpoken = languageSpoken;
  }

  speak() {
    /* ... */
  }
}

⬆ back to top

Use method chaining

This pattern is very useful in JavaScript and you see it in many libraries such as jQuery and Lodash. It allows your code to be expressive, and less verbose. For that reason, I say, use method chaining and take a look at how clean your code will be. In your class functions, simply return this at the end of every function, and you can chain further class methods onto it.

Bad:

class Car {
  constructor(make, model, color) {
    this.make = make;
    this.model = model;
    this.color = color;
  }

  setMake(make) {
    this.make = make;
  }

  setModel(model) {
    this.model = model;
  }

  setColor(color) {
    this.color = color;
  }

  save() {
    console.log(this.make, this.model, this.color);
  }
}

const car = new Car("Ford", "F-150", "red");
car.setColor("pink");
car.save();

Good:

class Car {
  constructor(make, model, color) {
    this.make = make;
    this.model = model;
    this.color = color;
  }

  setMake(make) {
    this.make = make;
    // NOTE: Returning this for chaining
    return this;
  }

  setModel(model) {
    this.model = model;
    // NOTE: Returning this for chaining
    return this;
  }

  setColor(color) {
    this.color = color;
    // NOTE: Returning this for chaining
    return this;
  }

  save() {
    console.log(this.make, this.model, this.color);
    // NOTE: Returning this for chaining
    return this;
  }
}

const car = new Car("Ford", "F-150", "red").setColor("pink").save();

⬆ back to top

Prefer composition over inheritance

As stated famously in Design Patterns by the Gang of Four, you should prefer composition over inheritance where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.

You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:

  1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
  2. You can reuse code from the base classes (Humans can move like all animals).
  3. You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).

Bad:

class Employee {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  // ...
}

// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee
class EmployeeTaxData extends Employee {
  constructor(ssn, salary) {
    super();
    this.ssn = ssn;
    this.salary = salary;
  }

  // ...
}

Good:

class EmployeeTaxData {
  constructor(ssn, salary) {
    this.ssn = ssn;
    this.salary = salary;
  }

  // ...
}

class Employee {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  setTaxData(ssn, salary) {
    this.taxData = new EmployeeTaxData(ssn, salary);
  }
  // ...
}

⬆ back to top

SOLID

Single Responsibility Principle (SRP)

As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.

Bad:

class UserSettings {
  constructor(user) {
    this.user = user;
  }

  changeSettings(settings) {
    if (this.verifyCredentials()) {
      // ...
    }
  }

  verifyCredentials() {
    // ...
  }
}

Good:

class UserAuth {
  constructor(user) {
    this.user = user;
  }

  verifyCredentials() {
    // ...
  }
}

class UserSettings {
  constructor(user) {
    this.user = user;
    this.auth = new UserAuth(user);
  }

  changeSettings(settings) {
    if (this.auth.verifyCredentials()) {
      // ...
    }
  }
}

⬆ back to top

Open/Closed Principle (OCP)

As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.

Bad:

class AjaxAdapter extends Adapter {
  constructor() {
    super();
    this.name = "ajaxAdapter";
  }
}

class NodeAdapter extends Adapter {
  constructor() {
    super();
    this.name = "nodeAdapter";
  }
}

class HttpRequester {
  constructor(adapter) {
    this.adapter = adapter;
  }

  fetch(url) {
    if (this.adapter.name === "ajaxAdapter") {
      return makeAjaxCall(url).then(response => {
        // transform response and return
      });
    } else if (this.adapter.name === "nodeAdapter") {
      return makeHttpCall(url).then(response => {
        // transform response and return
      });
    }
  }
}

function makeAjaxCall(url) {
  // request and return promise
}

function makeHttpCall(url) {
  // request and return promise
}

Good:

class AjaxAdapter extends Adapter {
  constructor() {
    super();
    this.name = "ajaxAdapter";
  }

  request(url) {
    // request and return promise
  }
}

class NodeAdapter extends Adapter {
  constructor() {
    super();
    this.name = "nodeAdapter";
  }

  request(url) {
    // request and return promise
  }
}

class HttpRequester {
  constructor(adapter) {
    this.adapter = adapter;
  }

  fetch(url) {
    return this.adapter.request(url).then(response => {
      // transform response and return
    });
  }
}

⬆ back to top

Liskov Substitution Principle (LSP)

This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition.

The best explanation for this is if you have a parent class and a child class, then the base class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble.

Bad:

class Rectangle {
  constructor() {
    this.width = 0;
    this.height = 0;
  }

  setColor(color) {
    // ...
  }

  render(area) {
    // ...
  }

  setWidth(width) {
    this.width = width;
  }

  setHeight(height) {
    this.height = height;
  }

  getArea() {
    return this.width * this.height;
  }
}

class Square extends Rectangle {
  setWidth(width) {
    this.width = width;
    this.height = width;
  }

  setHeight(height) {
    this.width = height;
    this.height = height;
  }
}

function renderLargeRectangles(rectangles) {
  rectangles.forEach(rectangle => {
    rectangle.setWidth(4);
    rectangle.setHeight(5);
    const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20.
    rectangle.render(area);
  });
}

const rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles(rectangles);

Good:

class Shape {
  setColor(color) {
    // ...
  }

  render(area) {
    // ...
  }
}

class Rectangle extends Shape {
  constructor(width, height) {
    super();
    this.width = width;
    this.height = height;
  }

  getArea() {
    return this.width * this.height;
  }
}

class Square extends Shape {
  constructor(length) {
    super();
    this.length = length;
  }

  getArea() {
    return this.length * this.length;
  }
}

function renderLargeShapes(shapes) {
  shapes.forEach(shape => {
    const area = shape.getArea();
    shape.render(area);
  });
}

const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];
renderLargeShapes(shapes);

⬆ back to top

Interface Segregation Principle (ISP)

JavaScript doesn't have interfaces so this principle doesn't apply as strictly as others. However, it's important and relevant even with JavaScript's lack of type system.

ISP states that "Clients should not be forced to depend upon interfaces that they do not use." Interfaces are implicit contracts in JavaScript because of duck typing.

A good example to look at that demonstrates this principle in JavaScript is for classes that require large settings objects. Not requiring clients to setup huge amounts of options is beneficial, because most of the time they won't need all of the settings. Making them optional helps prevent having a "fat interface".

Bad:

class DOMTraverser {
  constructor(settings) {
    this.settings = settings;
    this.setup();
  }

  setup() {
    this.rootNode = this.settings.rootNode;
    this.settings.animationModule.setup();
  }

  traverse() {
    // ...
  }
}

const $ = new DOMTraverser({
  rootNode: document.getElementsByTagName("body"),
  animationModule() {} // Most of the time, we won't need to animate when traversing.
  // ...
});

Good:

class DOMTraverser {
  constructor(settings) {
    this.settings = settings;
    this.options = settings.options;
    this.setup();
  }

  setup() {
    this.rootNode = this.settings.rootNode;
    this.setupOptions();
  }

  setupOptions() {
    if (this.options.animationModule) {
      // ...
    }
  }

  traverse() {
    // ...
  }
}

const $ = new DOMTraverser({
  rootNode: document.getElementsByTagName("body"),
  options: {
    animationModule() {}
  }
});

⬆ back to top

Dependency Inversion Principle (DIP)

This principle states two essential things:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend on abstractions.

This can be hard to understand at first, but if you've worked with AngularJS, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.

As stated previously, JavaScript doesn't have interfaces so the abstractions that are depended upon are implicit contracts. That is to say, the methods and properties that an object/class exposes to another object/class. In the example below, the implicit contract is that any Request module for an InventoryTracker will have a requestItems method.

Bad:

class InventoryRequester {
  constructor() {
    this.REQ_METHODS = ["HTTP"];
  }

  requestItem(item) {
    // ...
  }
}

class InventoryTracker {
  constructor(items) {
    this.items = items;

    // BAD: We have created a dependency on a specific request implementation.
    // We should just have requestItems depend on a request method: `request`
    this.requester = new InventoryRequester();
  }

  requestItems() {
    this.items.forEach(item => {
      this.requester.requestItem(item);
    });
  }
}

const inventoryTracker = new InventoryTracker(["apples", "bananas"]);
inventoryTracker.requestItems();

Good:

class InventoryTracker {
  constructor(items, requester) {
    this.items = items;
    this.requester = requester;
  }

  requestItems() {
    this.items.forEach(item => {
      this.requester.requestItem(item);
    });
  }
}

class InventoryRequesterV1 {
  constructor() {
    this.REQ_METHODS = ["HTTP"];
  }

  requestItem(item) {
    // ...
  }
}

class InventoryRequesterV2 {
  constructor() {
    this.REQ_METHODS = ["WS"];
  }

  requestItem(item) {
    // ...
  }
}

// By constructing our dependencies externally and injecting them, we can easily
// substitute our request module for a fancy new one that uses WebSockets.
const inventoryTracker = new InventoryTracker(
  ["apples", "bananas"],
  new InventoryRequesterV2()
);
inventoryTracker.requestItems();

⬆ back to top

Testing

Testing is more important than shipping. If you have no tests or an inadequate amount, then every time you ship code you won't be sure that you didn't break anything. Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches) is how you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use a good coverage tool.

There's no excuse to not write tests. There are plenty of good JS test frameworks, so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one.

Single concept per test

Bad:

import assert from "assert";

describe("MomentJS", () => {
  it("handles date boundaries", () => {
    let date;

    date = new MomentJS("1/1/2015");
    date.addDays(30);
    assert.equal("1/31/2015", date);

    date = new MomentJS("2/1/2016");
    date.addDays(28);
    assert.equal("02/29/2016", date);

    date = new MomentJS("2/1/2015");
    date.addDays(28);
    assert.equal("03/01/2015", date);
  });
});

Good:

import assert from "assert";

describe("MomentJS", () => {
  it("handles 30-day months", () => {
    const date = new MomentJS("1/1/2015");
    date.addDays(30);
    assert.equal("1/31/2015", date);
  });

  it("handles leap year", () => {
    const date = new MomentJS("2/1/2016");
    date.addDays(28);
    assert.equal("02/29/2016", date);
  });

  it("handles non-leap year", () => {
    const date = new MomentJS("2/1/2015");
    date.addDays(28);
    assert.equal("03/01/2015", date);
  });
});

⬆ back to top

Concurrency

Use Promises, not callbacks

Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6, Promises are a built-in global type. Use them!

Bad:

import { get } from "request";
import { writeFile } from "fs";

get(
  "https://en.wikipedia.org/wiki/Robert_Cecil_Martin",
  (requestErr, response, body) => {
    if (requestErr) {
      console.error(requestErr);
    } else {
      writeFile("article.html", body, writeErr => {
        if (writeErr) {
          console.error(writeErr);
        } else {
          console.log("File written");
        }
      });
    }
  }
);

Good:

import { get } from "request-promise";
import { writeFile } from "fs-extra";

get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
  .then(body => {
    return writeFile("article.html", body);
  })
  .then(() => {
    console.log("File written");
  })
  .catch(err => {
    console.error(err);
  });

⬆ back to top

Async/Await are even cleaner than Promises

Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await which offer an even cleaner solution. All you need is a function that is prefixed in an async keyword, and then you can write your logic imperatively without a then chain of functions. Use this if you can take advantage of ES2017/ES8 features today!

Bad:

import { get } from "request-promise";
import { writeFile } from "fs-extra";

get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
  .then(body => {
    return writeFile("article.html", body);
  })
  .then(() => {
    console.log("File written");
  })
  .catch(err => {
    console.error(err);
  });

Good:

import { get } from "request-promise";
import { writeFile } from "fs-extra";

async function getCleanCodeArticle() {
  try {
    const body = await get(
      "https://en.wikipedia.org/wiki/Robert_Cecil_Martin"
    );
    await writeFile("article.html", body);
    console.log("File written");
  } catch (err) {
    console.error(err);
  }
}

getCleanCodeArticle()

⬆ back to top

Error Handling

Thrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it's letting you know by stopping function execution on the current stack, killing the process (in Node), and notifying you in the console with a stack trace.

Don't ignore caught errors

Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Logging the error to the console (console.log) isn't much better as often times it can get lost in a sea of things printed to the console. If you wrap any bit of code in a try/catch it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.

Bad:

try {
  functionThatMightThrow();
} catch (error) {
  console.log(error);
}

Good:

try {
  functionThatMightThrow();
} catch (error) {
  // One option (more noisy than console.log):
  console.error(error);
  // Another option:
  notifyUserOfError(error);
  // Another option:
  reportErrorToService(error);
  // OR do all three!
}

Don't ignore rejected promises

For the same reason you shouldn't ignore caught errors from try/catch.

Bad:

getdata()
  .then(data => {
    functionThatMightThrow(data);
  })
  .catch(error => {
    console.log(error);
  });

Good:

getdata()
  .then(data => {
    functionThatMightThrow(data);
  })
  .catch(error => {
    // One option (more noisy than console.log):
    console.error(error);
    // Another option:
    notifyUserOfError(error);
    // Another option:
    reportErrorToService(error);
    // OR do all three!
  });

⬆ back to top

Formatting

Formatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point is DO NOT ARGUE over formatting. There are tons of tools to automate this. Use one! It's a waste of time and money for engineers to argue over formatting.

For things that don't fall under the purview of automatic formatting (indentation, tabs vs. spaces, double vs. single quotes, etc.) look here for some guidance.

Use consistent capitalization

JavaScript is untyped, so capitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, just be consistent.

Bad:

const DAYS_IN_WEEK = 7;
const daysInMonth = 30;

const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"];
const Artists = ["ACDC", "Led Zeppelin", "The Beatles"];

function eraseDatabase() {}
function restore_database() {}

class animal {}
class Alpaca {}

Good:

const DAYS_IN_WEEK = 7;
const DAYS_IN_MONTH = 30;

const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"];
const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"];

function eraseDatabase() {}
function restoreDatabase() {}

class Animal {}
class Alpaca {}

⬆ back to top

Function callers and callees should be close

If a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee. We tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way.

Bad:

class PerformanceReview {
  constructor(employee) {
    this.employee = employee;
  }

  lookupPeers() {
    return db.lookup(this.employee, "peers");
  }

  lookupManager() {
    return db.lookup(this.employee, "manager");
  }

  getPeerReviews() {
    const peers = this.lookupPeers();
    // ...
  }

  perfReview() {
    this.getPeerReviews();
    this.getManagerReview();
    this.getSelfReview();
  }

  getManagerReview() {
    const manager = this.lookupManager();
  }

  getSelfReview() {
    // ...
  }
}

const review = new PerformanceReview(employee);
review.perfReview();

Good:

class PerformanceReview {
  constructor(employee) {
    this.employee = employee;
  }

  perfReview() {
    this.getPeerReviews();
    this.getManagerReview();
    this.getSelfReview();
  }

  getPeerReviews() {
    const peers = this.lookupPeers();
    // ...
  }

  lookupPeers() {
    return db.lookup(this.employee, "peers");
  }

  getManagerReview() {
    const manager = this.lookupManager();
  }

  lookupManager() {
    return db.lookup(this.employee, "manager");
  }

  getSelfReview() {
    // ...
  }
}

const review = new PerformanceReview(employee);
review.perfReview();

⬆ back to top

Comments

Only comment things that have business logic complexity.

Comments are an apology, not a requirement. Good code mostly documents itself.

Bad:

function hashIt(data) {
  // The hash
  let hash = 0;

  // Length of string
  const length = data.length;

  // Loop through every character in data
  for (let i = 0; i < length; i++) {
    // Get character code.
    const char = data.charCodeAt(i);
    // Make the hash
    hash = (hash << 5) - hash + char;
    // Convert to 32-bit integer
    hash &= hash;
  }
}

Good:

function hashIt(data) {
  let hash = 0;
  const length = data.length;

  for (let i = 0; i < length; i++) {
    const char = data.charCodeAt(i);
    hash = (hash << 5) - hash + char;

    // Convert to 32-bit integer
    hash &= hash;
  }
}

⬆ back to top

Don't leave commented out code in your codebase

Version control exists for a reason. Leave old code in your history.

Bad:

doStuff();
// doOtherStuff();
// doSomeMoreStuff();
// doSoMuchStuff();

Good:

doStuff();

⬆ back to top

Don't have journal comments

Remember, use version control! There's no need for dead code, commented code, and especially journal comments. Use git log to get history!

Bad:

/**
 * 2016-12-20: Removed monads, didn't understand them (RM)
 * 2016-10-01: Improved using special monads (JP)
 * 2016-02-03: Removed type-checking (LI)
 * 2015-03-14: Added combine with type-checking (JR)
 */
function combine(a, b) {
  return a + b;
}

Good:

function combine(a, b) {
  return a + b;
}

⬆ back to top

Avoid positional markers

They usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code.

Bad:

////////////////////////////////////////////////////////////////////////////////
// Scope Model Instantiation
////////////////////////////////////////////////////////////////////////////////
$scope.model = {
  menu: "foo",
  nav: "bar"
};

////////////////////////////////////////////////////////////////////////////////
// Action setup
////////////////////////////////////////////////////////////////////////////////
const actions = function() {
  // ...
};

Good:

$scope.model = {
  menu: "foo",
  nav: "bar"
};

const actions = function() {
  // ...
};

⬆ back to top

Translation

This is also available in other languages:

⬆ back to top

clean-code-javascript's People

Contributors

alaycock avatar andersontr15 avatar b0yfriend avatar bsonmez avatar chaosbohne avatar danielstjules avatar davidvujic avatar foxyblocks avatar frappacchio avatar hemantpawar avatar iamken1204 avatar jordalgo avatar jsgao0 avatar justin0022 avatar kbariotis avatar kurtommy avatar maksugr avatar mariotacke avatar neatoro avatar ristomcintosh avatar rouzbeh84 avatar rudotriton avatar ryanmcdermott avatar sebastienelet avatar sney2002 avatar stewx avatar vasanthk avatar vinibrsl avatar vsemozhetbyt avatar yahkob avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clean-code-javascript's Issues

Default arguments

We should add some disclaimer in the "default arguments" section, since the example will work only if the argument passed is undefined, if the argument is null, it won't work in the second example, but it will work in the first one.

There's some improvements that can be made

Never ever, ever, under any circumstance, have duplicate code. There's no reason for it and it's quite possibly the worst sin you can commit as a professional developer.

I disagree. This simply is not true. Actually, there's ample evidence that the wrong abstraction can be far more costly than duplicate code. DRYing up code is generally a good idea to do, and for people who are new to the core concept itself it may be a good idea to remove duplication instantly, the moment it is spotted. However, allowing more evidence to accumulate before making that abstraction is usually the best approach. And in order to DRY your code, you should have the right automated tests that enable you to refactor, which brings me on to another criticism of your content as it currently stands - your testing section:

Testing is more important than shipping

I'm a massive fan of testing and TDD, but this is a poorly worded statement and not a good way to introduce the subject in my opinion. It kinda implies that you're choosing one or another. How about rewording to say something more positive (and accurate) such as "Excellent automated tests are key to constant incremental updates..." - you're saying the same thing effectively but in a more positive way that also links the connection between great tests and being able to ship often.

If you have no tests or an inadequate amount, then every time you ship code you won't be sure that you didn't break anything.

Which should open the door to a discussion on how to write tests that scale in such a way that they help you make modifications (either via new features or via refactoring) to your code. Many people who start off with testing do it badly by over-using mocks for example, which tightly couples their tests to their implementation details, making it actually harder to keep shipping, not easier. A discussion on these techniques and an improvement in your overall description is required in my opinion.

Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches) is how you achieve very high confidence and developer peace of mind.

I disagree to a point here - 100% coverage can be misleading as a measure of confidence. Sure, code coverage tools are good in that they can help you spot areas of your code that are not covered by tests (more of an issue for people who are not doing TDD of course), but having 100% coverage doesn't mean your code is well tested, or even fully tested. You can have 100% code coverage and have almost nothing properly tested.

I could write a single test that covers a huge chunk of my code base but doesn't really prove anything that matters.

Tests should be written around behaviours that the business cares about, and if you're doing TDD and doing it well this should mean you basically always have 100% code coverage + you're confident that your tests will fail if the behaviours you care about no longer work as expected. This is what really matters.

This means that in addition to having a great testing framework, you also need to use a good coverage tool.

Disagree. It can be helpful, but you don't need it.

Use getters and setters section

The "Use getters and setters" section describes that it is hard to enforce the pattern, because JavaScript don't have the public and private keywords. I think this is actually an issue with JavaScript classes. With functions, properties can easily be private. Here's an example (also without the get and set keywords, that I think will cause confusion):

function myObject() {
  // this one is private
  let myPrivateProperty = 'hello';

  // a "getter", made public via the return statement below
  const getMyProperty = () => myPrivateProperty;

  // a "setter", made public via the return statement below
  const setMyProperty = (val) => myPrivateProperty = val;
  
  return {
    getMyProperty,
    setMyProperty
  };
}

disagree with 'Don't over-optimize'

qq 20170119200848

The time log shows us that maybe it's better to calculate the length and store it .

From 0.065ms to 0.035ms.

later: Sorry that I did't see In modern browsers, this is optimized.;

"Use method chaining" and Law of Demeter

I think this part of the guide falls into the trap of thinking that the Law of Demeter (LOD) is simply about multiple method calls or the "2/3 dot rule".

It's more about "not talking to strangers". The paper "The Paperboy, The Wallet and The Law Of Demeter" sums it up nicely.

If your functions return the same type, it's totally fine. In your example, you're using the builder pattern, which always returns the same type to allow further operations.

Another example of not violating LOD would be a functional pipeline transforming an array:

const list = [1, 2, 3, 4, 5]

list.map(...).reduce(...).filter(...).concat(...) // not a violation of LOD

Hope this helps!

Not explicit function name

In section Function names should say what they do you're explicitly saying that you're adding a month to a date, addMonthToDate().

In section Remove duplicate code you're showing the employees list using showList().

Shouldn't that be showEmployeesList() as well, in order to explicitly tell what will be shown, so you just have to pass the type of the employee as an argument (managers or developers in that context)?

I'm not really sure about it, which is why I wanted to discuss about. Thanks for this great work!

Question about two principles

I often find myself choosing between Don't use flags as function parameters and Remove duplicate code.

In the example for Don't use flags as function parameters we have as the suggested approach:

function createTempFile(name) {
  fs.create('./temp/' + name);
}

function createFile(name) {
  fs.create(name);
}

This has duplicated code (although just 1 line in this case) in the same way that the bad example for Remove duplicate code has:

function showDeveloperList(developers) {
...
    var githubLink = developer.getGithubLink();
...
}

function showManagerList(managers) {
...
    var portfolio = manager.getMBAProjects();
...
}

In the Remove duplicate code case we are suggested to instead do:

function showList(employees) {
...
    if (employee.type === 'manager') {
      portfolio = employee.getMBAProjects();
    } else {
      portfolio = employee.getGithubLink();
    }
...
}

My question is, how do you decide when to keep code DRY, or to keep functions only doing 1 thing (not multiple variations of 1 thing = many things)?

I'd love some thoughts on this. Thanks!

method chaining - minor typo

Nice work, very useful! In the section on 'method chaining', the setMake functions:

setMake(make) { this.name = name; }

should it be:

setMake(make) { this.make = make; }

Script to extract JavaScript fragments from a markdown file

Most likely there are many better solutions for this, but here it is my quick attempt.

Usage: md.extract-js.js markdown-file.md.

Extracted .js files will be created in the markdown-file.md.extracted-js directory next to markdown-file.md. Each file has this name template: numberOfFragment.numberOfFirstLine-numberOfLastLine.js.

A contributor can run a linter on the whole directory or run each file with Node.js. There will be many linter errors or runtime errors due to many undeclared (or unused) variables, so some filter work will be needed.

In our case, the odd filenames are bad examples, the even filenames are good ones.

Here is a new PR from this script's work.

Mutation testing

What are your thoughts on mutation testing?

Background info:
Mutation testing is a technique used to measure the quality of your tests. Code coverage only measures which code is executed during testing, mutation testing actually tests your tests. This is done by inserting bugs (mutations) into your code such as replacing > with < or >=.

After a mutation has been applied to the code, all tests belonging to that mutation are executed. If a tests fails due to mutated code, all is well. Your tests managed to detect the bug. If no tests failed, you may have an issue.

The current guide says:

the main point is to just make sure you are reaching your coverage goals before launching any feature

This does not mean that you have properly tested your application. Unfortunately there are people who temporarily disable assertions, only to forget to turn them back on again. Sometimes people even write tests without assertions (or bad ones) just for the sake of reaching their code coverage goals.

So, what are the downsides of mutation testing (in JavaScript)?

  • It's (relatively) slow because tests have to be executed many, many times.
  • It's hard to write a mutation testing framework for JavaScript. There are a lot of combinations of compilers, test frameworks and test runners.

Unnecessary closure/IIFE?

In the advice about private members, what's the point of the extra IIFE over Employee definition?

var Employee = (function() {
  function Employee(name) {
    this.getName = function() {
      return name;
    };
  }

  return Employee;
}());

Since there are no extra variables in the outer function, this snippet could as well read:

function Employee(name) {
  this.getName = function() {
    return name;
  };
 }

Ternary Operators

What's the standard for Ternary Operators? I find that I use them a lot in my js code. Back in college we used to have these rules:

  1. Absolutely 1 condition only
  2. Atomic data in the true/false section
  3. The ternary statement is in its own line, not nesting between other statements.

LSP example: is it interpreted in the right way?

I wanted to state that in my opinion the "Good" part on the section on Liskov Substitution Principle is not a good interpretation.
(I'm really not sure about it, it's a feeling, so forgive me if I'm the one who is interpreting in the wrong way.)

What I think is that the "Bad" and "Good" are too different to be a refactoring example:

  • they are not easily refactorable one in the other, because they are not sharing the inheritance structure
  • it's not clear what problem the code tries to solve
  • the principle is not even applicable in the "Good" example, because there are no instanced objects of type Shape:

    If Rectangle (S) is a subtype of Shape (T), then objects of type Shape (T) may be replaced with objects of type Rectangle (S)

  • the "Good" example uses a switch (shape.constructor.name) which is very not-object-oriented:
    • it hardcodes the class name as a string in the code
    • it's not open to addition of new classes
    • it violates the Avoid conditionals principle, which suggests itself to use classes
    • it violates the Avoid type-checking (I think the Ruby world suggestion of "Tell, don't Ask" would be a good explanation of this principle!)

I'd be glad to discuss and help to build a more correct example, if anyone feels the same on my doubts.

Thanks for the great work!

Legal comments in source files

You said:
Avoid legal comments in source files
That's what your LICENSE file at the top of your source tree is for

I partially disagree.
1\ You can combine multiple licences in your source tree
2\ You can not expect that everyone will take all your files in their project (so with time, the original license can be lost)
3\ When someone snoop your code on your web-based stuff in production, the LICENSE file is often absent or not reachable.

So, as author, you must be absolutely clear about your licenses intentions, especially if you want protects freedom of users of your code users. Here some clue :
https://www.gnu.org/philosophy/javascript-trap.html#AppendixA

Open/Closed Principle (OCP) example

I think Open/Closed Principle is not about ability to extend module functionality during app runtime. It's more about writing code which doesn't require from developers changing existing code during adding new functionality. I thought about this example and I think it could be slightly changed. Let's say we have class responsible for fetch data, handle response and return promise. It can be configured to use in both browser and node js environment. This could be bad example:

class AjaxAdapter extends Adapter {
  constructor() {
    super();
    this.name = 'ajaxAdapter';
  }
}

class NodeAdapter extends Adapter {
  constructor() {
    super();
    this.name = 'nodeAdapter';
  }
}

class httpRequester {
  constructor(adapter) {
    this.adapter = adapter;
  }

  fetch(url) {
    if (this.adapter.name === 'ajaxAdapter') {
      return makeAjaxCall(url).then(response => {
        // transform response and return
      });
    } else if(this.adapter.name === 'httpNodeAdapter') {
      return makeHttpCall(url).then(response => {
        // transform response and return
      });
    }
  }
}

function makeAjaxCall(url) {
  // request and return promise
}

function makeHttpCall(url) {
  // request and return promise
}

This is bad, because if we would like to add new adapter, we have to change httpRequester class. We can fix it this way:

class AjaxAdapter extends Adapter {
  constructor() {
    super();
    this.name = 'ajaxAdapter';
  }

  request(url) {
    // request and return promise
  }
}

class NodeAdapter extends Adapter {
  constructor() {
    super();
    this.name = 'nodeAdapter';
  }

  request(url) {
    // request and return promise
  }
}

class httpRequester {
  constructor(adapter) {
    this.adapter = adapter;
  }

  fetch(url) {
    return this.adapter.request(url).then(response => {
      // transform response and return
    });
  }
}

What do You think about that ?

Maybe remove "Short-circuiting is cleaner than conditionals"?

Because:

a) You already have "Use default arguments instead of short circuiting", which is a better approach (if supported), and

b) I have seen bugs introduced by writing a short circuit when the function is supposed to accept falsy values:

function double(x) {
   var value = x || -1;
   return value * 2;
}

double(0);  // returns -2, should return 0

Fix Object.assign example

The Object.assign example is currently incorrect.

function createMenu(config) {
  Object.assign(config, {
    title: 'Foo',
    body: 'Bar',
    buttonText: 'Baz',
    cancellable: true
  });
}

createMenu({ title: 'Not Foo' });

The title property will always be set to 'Foo'!

I was going to make a PR with a fix, but the approach really depends on whether the mutation of config is desirable.

How I would do it (this does not behave identically to the "bad" example):

function createMenu(config) {
  // makes a copy of `config`, with default values
  config = Object.assign({
    title: 'Foo',
    body: 'Bar',
    buttonText: 'Baz',
    cancellable: true
  }, config);
}

How you could do it with mutation (this is identical to the "bad" example):

function createMenu(config) {
  // mutates `config`, setting default values
  Object.assign(config, Object.assign({
    title: 'Foo',
    body: 'Bar',
    buttonText: 'Baz',
    cancellable: true
  }, config));
}

What about Magic strings?

Do you think that can be good to include something about magic strings?

Bad:

let posts = getPostsFromCategory('sports');

Good:

const categories = {
  sports: 'sports',
  economy: 'economy'
};

let posts = getPostsFromCategory(categories.sports);

Composition / Inheritence vs Inheritence thoughts

So I thought I'd personally share some philosophies that helped me personally distinguish when to use one over the other. Initially as a novice developer I loved convention over configuration and therefore loved inheritance, but nowadays I've come to greatly appreciate composition. However I've realized there's a very concrete reason for this:

Frameworks benefit from convention.
Libraries benefit from composition.

I found that in a framework, it's acceptable to build the assumption / expectation that fellow developers will have to eventually learn all the conventions of your framework in order to leverage it and move quickly. It is almost a form of 'environment' in which you choose to develop in, and in so doing, the conventions allow you to move quickly and create reusable, shareable modules with little to no learning curve across modules. However, this is an expensive requirement as there is a greater learning curve for new engineers joining the project / framework for them to gain what is essentially "common knowledge" of the conventions in the framework. Simply looking at code in angular, ember, and react you see properties of objects that are not quite self-explanatory on their own or you may seek functionality or behavior that requires a certain degree of knowledge of the framework in order to solve. But once this knowledge is common you can rapidly develop and focus on larger scale problems.

When developing a library, you can't expect knowledge of your conventions. Libraries are far more likely to be moved and used and added and removed. Composeable code creates a sort of self-documenting approach to someone joining the codebase or picking up the code. It becomes clearer to see how or why a library or object is behaving in a specific way because the behavior configuration is laid out before you vs being handled using hand-waving magic under the hood. All behavior is explicitly configured and created. This is handy for when a developer may only briefly interact with your code such as a library in order to achieve what they need and then will likely move on to focus on unrelated code (such as another section of their application).

TL;DR:

A possible example of inheritence / convention vs composeable / configuration is are you developing a framework vs a library.

Is the user entrenching themself completely in your codebase and expected to learn all the conventions, or is their interaction with your code only used for a brief subset of their application.

Composeable is self-documenting and can be gleamed from the surface quickly. Inheritence requires gaining knowledge of internal behavior but allows large productivity rapidly.

Use `const` and `let` over `var`

The current code samples are not consistent, mix a half var and a half let (and a few const).

We may need a unified rule for the usage of const/let and apply it to the code samples, as you mentioned in the second principle Use ES6 constants when variable values do not change, or your code is not clean. 😉

"If Haskell were an IPA ..."

From the guide: "If Haskell were an IPA then JavaScript would be an O'Douls."

I have no idea what you're talking about. JS programmers aren't required to know beer brands, let alone country-specific beer brands. A user that doesn't know where Haskell and JS stood on the functional spectrum would be pretty lost here.

In general, a programming guide should require zero knowledge outside the field of programming.

If the comparison just has to be there, here's a suggestion:
"If Haskell were a good steak, then JS would be a sandwich with slices of meat.

Opionion on `Function arguments`

Zero arguments is the ideal case.

I don't think zero arguments is ideal, because it only applies to impure functions and objects or classes methods.

Actually pure functions might have zero arguments, but they would be kind of pointless right?

Since the guide favors single purpose pure functions, having zero arguments wouldn't make sense. In my opinion one argument is the ideal. And zero is just ok if the function is not pure or is a method of an object or class.

Just an opionion.

Modularize the huge markdown file

Since there are open issues with people translating the big markdown file - #55 #99 #146 ..., it would be a shame to have all the code duplicated in all of them. We could create a folder with all the snippets which could be then included by the different translation. It could be done, with

I would like to create a PR if you are willing to include this in your repo, but it will be consist of a huge amount of changes and a lot to review. Let me know!

Destructuring array will error if no match

const [, city, zipCode] = address.match(cityZipCodeRegex);

This will error if the address doesn't match, but can be fixed with:

const [, city, zipCode] = address.match(cityZipCodeRegex) || [];

Suggest url,filename mvc architecture file names?

Hi @ryanmcdermott ,

This is not an issue, How to we given the filenames is lowerCamelCase ,UpperCamelCase, file_name.js , file-name.js like that and standard format is there ?

If we request api call means how we mention the url ?

Request URL:https://serviceprovider.com/api/power-details
Request URL:https://serviceprovider.com/api/power_details
Request URL:https://serviceprovider.com/api/powerDetails
Request URL:https://serviceprovider.com/api/Powerdetails

like the above any standard ?

If we create an MVC architecture means how we use this file name

Model
- loginModel.html
- login-model.html
- login_model.html
Views
- loginView.js
- login-iew.js
- login_view.js
Controller
- loginController.js
- login-Controller.js
- login_Controller.js

If we create url means how we use ?

Please suggest standard format

Prefer composition over inheritance

As the rule from title tells us, we should favor composition when we code.
So maybe it's worth to replace all examples using class with proper ones based on composition?

Let's take the "Avoid conditionals" section for instance. It shows the example of inheritance while the goal was to encourage the developer to use composition. Below you can see how the definition of different airplanes could look like (using composition):

const Airplane = {
  getName() {
    return `${this.name}`
  }
}

const AirbusA380 = { 
  name: 'Airbus A380',
  getName() {
    return  `${Airplane.getName.call(this)} of ${this.airline}`
  }
}

const Cessna = { 
  name: 'Cessna'
}


// define factory functions (airbusA380, cessna)
const airbusA380 = (state) => Object.assign(
  {},
  Airplane,
  AirbusA380,
  state
)

const cessna = (state) => Object.assign(
  {},
  Airplane,
  Cessna,
  state
)

// create instances of airplanes
const emiratesAirbus = airbusA380({
  airline: 'Emirates'
})

const privateCessnaJet = cessna()

console.log(emiratesAirbus.getName()) // prints "Airbus A380 of Emirates"
console.log(privateCessnaJet.getName()) // prints "Cessna"

What do you think about replacing all class examples with composition-based ones?

Avoid changing function input objects

A thing I see very often is when we are changing a function's object variables. Those variables are passed by reference and this is a side effect. I would propose of adding it to the Side Effects section.

Async/Await example is incorrect

In section Async/Await are even cleaner than Promises there are too many awaits, the ones on require() calls are not necessary.

I believe the code should be:

async function getCleanCodeArticle() {
  try {
    const response = await require('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');
    await require('fs-promise').writeFile('article.html', response);
    console.log('File written');
  } catch(err) {
    console.error(err);
  }
}

Though I would execute the require() calls in the code outside the function, in this and in all other examples.

Would recommend destructuring in function args 2 or less

This is absolutely not helpful, when you are trying to find out what kind of keys do the config object accept.

function createMenu(config) {
  // ...
}

createMenu({
  title: 'Foo',
  body: 'Bar',
  buttonText: 'Baz',
  cancellable: true
});

This however makes it perfectly clean exactly which keys are used:

function createMenu({ title, body, buttonText, cancellable }) {
  // ...
}

There are no sneaky magic properties accessed in the call chain later, since you don't have the reference to the original config object. I would highly recommend suggesting this version. Also while coding, if you have a linter, it will tell you if you have an unused prop in the destrucutured object while it will have no chance of warning you if you just take it as a regular argument.

'Use getters and setters' inconsistency

// It doesn't have to be prefixed with get or set to be a getter/setter

Well, how we can distinguish them from methods? With the example used there, the heading should be 'Prefer methods to simple properties and getters / setters'.

Variables with similar names prone to typing mistakes?

Let's say you have location and locations one next to each other, could this to lead to typing errors if you mistakenly write an extra s?

The closest I found in clean-code-javascript was Avoid Mental Mapping:

locations.forEach((location) => {
  ...
});

In the previous example, a proper editor (or its extension) could rapidly find out that location is not being used if you only used locations instead.

But what about in the following case?

function processLocationByExploringOtherLocations(location, locations) {
  ...
}

location and locations have the exact same priority for any editor, should we use something like locationsList instead?

Also, I am well aware that in this case TypeScript or flow would have recognized a typing mistake by simple checking their type. However, there are still many projects which do not use either of them.

Don't use objects as arguments.

Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument.

Since JavaScript allows us to make objects on the fly, without a lot of class boilerplate, you can use an object if you are finding yourself needing a lot of arguments.

Unless there are multiple optional arguments it does more harm than good to pass an object with arguments.

  1. Your IDE has no idea what arguments the function is expecting so hinting is a no go.
  2. The user has no idea what the options are without good documentation.
  3. func({foo: "bar", bar: "foo"}) looks worse than func("bar", "foo")

ES version for async functions

First, thanks a lot for this guide. Love it!
I just wanted to point out one little mistake.

Promises are a very clean alternative to callbacks, but ES7 brings async and await which offer an even cleaner solution. All you need is a function that is prefixed in an async keyword, and then you can write your logic imperatively without a then chain of functions. Use this if you can take advantage of ES7 features today!

Actually ES2016 (or ES7) only added two features: Array.prototype.includes and the exponentiation operator.

Async/Await is featured in ES2017 (or ES8).

Add info to "Avoid conditionals" about smelly code and open/closed principle

I don't think that the provided info about why not use switches in this section is complete. Maybe we should add info about smelly code, the strategy pattern and open/closed principles.

In this speak/presentation it is all made clear why not using switches. And it has not so much to do with functions doing on thing, but more about the open/closed principle and that with adding/removing/editing one case you just "touched" all cases in the switch and all have to be tested again.

Also he added a example using the strategy pattern to refactor the switch without violating the "open/closed principle". I like that example very much.

"Function arguments (2 or less ideally)" example seems dubious

Hey, thanks for the work on this - very nice!

The suggestion of using a config object to reduce the number of function arguments does not solve the underlying problem and is really just cheating - the function still takes four inputs and you still have to test every permutation, it just pretends to only take one input :)

In my opinion it's actually worse because rather than declaring the parameters explicitly it presents the consumer with an opaque method signature:

function createMenu(menuConfig)

If I'm writing code that calls this function I now have to read the full implementation of the function to find out which magic property names are expected within the config object, rather than just read the signature. Or you could add jsdoc for the function, but then you've got a maintenance problem.

There must be a better way to reduce the number of parameters, maybe currying?

Suggestion: Prefer iterators dependent on the variable's name

I figured out that for most complex code structures where I need nested loops due to performance, I can more easily read them once I chose to use iterators based on the variable's (object's or array's) name. I typically use the leading character as the iterator (e.g. dataset => d) and a trailing l to imply the length (e.g. dataset => dl).

While I know that functional programming is easier to read (e.g. using Object.values(dataset).forEach((chunk, c) => {}) it's hardly avoidable in timing-relevant methods and complex sorting algorithms that need performant behaviours (e.g. an update or render loop in a game engine).

Anyways, here's an example. Let me know whatcha think.

BAD example

const dataset = [{ foo: [1,2,3,4], bar: [1,2,3,4] }];

for (let i in dataset) {
    let chunk = dataset[i];
    for (let j = 0, l = chunk.length; j < l; j++) {
        console.log(chunk[j]); // you get the point
    }
}

GOOD example

const dataset = [{ foo: [1,2,3,4], bar: [1,2,3,4] }];

for (let d in dataset) {
    let chunk = dataset[d];
    for (let c = 0, cl = chunk.length; c < cl; c++) {
        console.log(chunk[c]); // you get the point
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.