Javascript clean code: Avoid passing booleans to functions

Javascript clean code: Avoid passing booleans to functions

1. Problem

Sometimes we’d like a function to behave differently in certain conditions. So a common approach is to pass a boolean parameter, also known as a flag. While this may be initially convenient it is widely considered a bad practice and a code smell.

A flag is used to alter the behavior of a function based on the context in which it is used. It is a good signal that a function is doing more than one thing and is not cohesive.

// ❌ Avoid using boolean flags in functions
distance(pointA, pointB, true)

// ✅ Instead, split the logic in two separate functions
distanceInKilometers(pointA, pointB)
distanceInMiles(pointA, pointB)

2. Solution

The single responsibility principle is not the only problem with flags. Booleans in function parameters hurt readability as well. A function call like the following doesn’t tell you much about what the flag does or what you should expect.

distance(pointA, pointB, true)

It obviously calculates the distance between two points. But what does the true stand for? In order to find out you’d need to inspect it. But you shouldn’t have to go through the implementation of each function to understand it.

Even if a named variable is passed to the function it won’t give you enough context. If the boolean variable was named isKilometers how could you know what it would do if false was passed? Is it going to use miles, meters or something else?

When Can It Be Okay?

Single argument functions that are named properly make a good exception to the rule. To me, the following code is clear enough and leaves no ambiguity on what it is doing.

setLoading(true)

If you absolutely must pass a boolean make sure that you make its purpose as obvious as possible. In JavaScript you may pass an object to achieve that. This way you force the caller to explicitly write down the flag’s property.

distance({
  from: pointA,
  to: pointB,
  isKilometers: true,
})

The potential problems we mentioned above are valid, but at least you leave no ambiguity about what the flag does.

3. Conclusion

  • Boolean flags are a code smell that can cause debugging and maintainability problems if left unchecked

  • Flags are not a best practice because they reduce the cohesion of a function. It does more than one thing.

  • Booleans make it hard to understand what a function does base on the call site.

  • Boolean arguments should generally be avoided but there are still exceptions to the rule.

  • Single argument functions and passing an object with named values improves the readability.