Coding Rules

Rules for writing robust, maintainable code

Rule 3: Don't use unnecessary conditionals (if, switch...)

When a piece of code contains an if condition, the code can take 2 paths. If the piece of code contains two nested if conditions, the code can take 4. If there are three the code can take 8 paths.

Each of these paths can hide a bug. The fewer conditionals there are, the fewer edge cases there are, and the more likely it is to come across the bugs when testing.

āŒ Don't:

async function getData(ids: string[]) {
  if (ids.length === 0) return [];
  if (ids.length === 1) return [await db.findOne(ids[0])];
  return db.find(ids);
}

In this example, the code may behave differently whether there is 0, 1, or more elements, and will need to have three tests to make sure it works properly.

The three cases may also have subtle differences that will not be detected while testing but may cause a bug in production.

āœ… Do:

async function getData(ids: string[]) {
  return db.find(ids);
}