«

Code smells in PHP - Boolean parameters

This isn’t one of the most common code smells you’ll hear of, but I certainly think it deserves to be on the list. To me, boolean parameters in functions and methods generally indicate that the function in question has a split inside where the code can go one of two ways, often doing more than one thing!

Lets have a look at what might happen when you come across with a method with a boolean parameter.

foreach($cart->getTotals(true) as $total) {

    //...

}

What does this parameter do? Format the totals maybe? Include tax? It really could be anything. The person reading this code would have to go to the getTotals method declaration in order to find out. If someone has to jump around in your code to understand what it does, then maybe you’re not being as explicit as you could be.

Lets pretend that boolean was in fact telling the class to include tax in those totals. Maybe it could be written as:

foreach($cart->getTotalsIncludingTax() as $total) {

    //...

}

By dropping the additional parameter, we’ve made our code so much more readable with pretty much no additional effort. We might end up with a few more methods, but the fact that they make our code so much more readable is something I can live with.