Avoid Boolean Parameters

 

Yesterday we found out why calling functions with null argument values causes developer confusion. We also discovered a simple solution to the problem.

Today we’ll explore a similar predicament with boolean parameters.

Let’s get into it.

Check out this line of code:

  var customers = GetCustomers(true);

Did you wonder what the ‘true’ meant?

Let’s navigate to the function definition:

  public Customers[] GetCustomers(bool isActive)
  {
     // ... 
  }

Right—in our previous call to GetCustomer(true) we were only interested in the active customers. We’re now understanding the behaviour better.

Navigating to the function definition disrupted our thought process. Whenever we write code that creates further questions in a developer’s mind as to the intended code behaviour, we have slipped up. When we cause the reader of our code to pause and have to wonder what is going on we have failed. We want to avoid those situations and express ourselves in our programming as clearly as we can manage.

OK. How do we express ourselves more explicitly?

Let’s do away with the boolean parameter and create a function for each boolean value:

  var customers = GetActiveCustomers();

and 

  var customers = GetInactiveCustomers();

Isn’t this just so much clearer? 

Yes, it is much better. However, wouldn’t this mean that we will have two copies of the same code? 

Not necessarily. Callers will see and use GetActiveCustomers() and GetInactiveCustomers() but that doesn’t mean that we cannot retain the function with the boolean parameter—as long as it’s private and hidden away:

  private Customers[] GetCustomers(bool isActive)
  {
     // ... 
  }

  public Customers[] GetActiveCustomers() 
  {
     return GetCustomers(true);
  }

  public Customers[] GetInactiveCustomers() 
  {
     return GetCustomers(false);
  }

These function re-definitions implicitly specify the meaning of the boolean parameter on the pass-through calls: true is ‘active’ and false ‘inactive’, respectively.

So, it’s not so much about avoiding boolean parameters altogether but more about not exposing them in a function or method to callers who may be confused about the purpose of the boolean. As mentioned, offering two functions, one for the boolean argument being true and one for it being false, is more explicit.

In conclusion, avoid boolean parameters on your public functions and methods. 

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply