DEV Community

56kode
56kode

Posted on

Clean code: why boolean flags in function parameters are a code smell

Boolean flags in function parameters can make your code harder to read and maintain. Let's see why you should avoid them and what you can do instead.

The problem with boolean flags

Using a boolean parameter often means your function does two different things, breaking the Single Responsibility Principle (SRP). Here's a typical example:

function createFile(name, isTemp) {
  if (isTemp) {
    fs.create(`./temp/${name}`);
  } else {
    fs.create(name);
  }
}
Enter fullscreen mode Exit fullscreen mode

This might look simple, but it has several problems:

  1. Unclear function calls: Reading the code, it's hard to know what the boolean means:
   createFile("log.txt", true);  // What does 'true' mean here?
Enter fullscreen mode Exit fullscreen mode
  1. Two functions in one: The boolean works like a switch, making the function do different things

  2. Testing gets harder: You need to check both ways the function can work

  3. Hard to add features: If you need a third option later, you might add another boolean, making things worse

A better way to write it

Split the function into two separate ones, each doing one thing:

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

function createTempFile(name) {
  createFile(`./temp/${name}`);
}
Enter fullscreen mode Exit fullscreen mode

This gives you:

  1. Clear names: createTempFile("log.txt") tells you exactly what it does

  2. Simple logic: Each function does just one thing

  3. Easy testing: You only need to test one thing per function

  4. Simple to add features: Need something new? Add a new function without changing the old ones

More examples

This idea works in many situations. Here are some cases:

Login system

// ❌ Bad
function authenticate(user, isAdmin) {
  if (isAdmin) {
    // Admin login logic
  } else {
    // Regular user login logic
  }
}

// ✅ Good 
function authenticateUser(user) {
  // Regular user login logic
}

function authenticateAdmin(user) {
  // Admin login logic
}
Enter fullscreen mode Exit fullscreen mode

Email system

// ❌ Bad
function sendEmail(user, isHtmlFormat) {
  if (isHtmlFormat) {
    // Send HTML email
  } else {
    // Send plain text email
  }
}

// ✅ Good
function sendPlainTextEmail(user) {
  // Send plain text email
}

function sendHtmlEmail(user) {
  // Send HTML email
}
Enter fullscreen mode Exit fullscreen mode

To sum up

Boolean flags in function parameters often show that a function tries to do too much. Making separate, focused functions creates code that is:

  • Easy to read
  • Easy to test
  • Easy to fix
  • Easy to change

Next time you want to add a boolean parameter, think about making two functions instead.


Have you tried splitting functions like this in your code? Did it help? Let me know in the comments!

Top comments (0)