DEV Community

Andrei Xavier de Oliveira Calazans
Andrei Xavier de Oliveira Calazans

Posted on

Do one thing at a time - prefering composition over branching logic

A simple yet powerful yea - do one thing at a time. Over time you will notice we apply that idea to many patterns in coding.

Pattern to use: prefer extracting and composing differences over using boolean flags:

Simple example is a setter function that uses a different key based on a boolean:

async function setData(data, isLoggedIn) {
  // ...ignore
  const storeKey = isLoggedIn ? 'logged_in_key' : 'logged_out_key';
  await setStoreData(storeKey, data);
  return true;
}
Enter fullscreen mode Exit fullscreen mode

It's best instead to extract storeKey as an argument

async function setData(data, storeKey) {
  // ...ignore
  await setStoreData(storeKey, data);
  return true;
}
Enter fullscreen mode Exit fullscreen mode

While the above example is simple in projects we see many make this mistake.

Classes are typically catch-all places of branching logic.

Tip: everytime you see a branching logic question yourself if it won't benefit from composition.

ps: This is a post zero of a series on writing better code, follow me for more

Top comments (1)

Collapse
 
bitmaybewise profile image
Hercules Lemke Merscher

Good one. A boolean parameter is usually a code smell!