We’ve probably had a time where we’ve added a boolean as a function parameter more than once and been satisfied and proud with our judgement. I definitely have at some point. Booleans as a function parameter are an example of code smell. For anyone new to the phrase, code smell is an indication in your code of a deeper problem. Why?
Restricting
A boolean is a datatype with two possibilities. True or False; Either Or. When you create a function that takes a boolean as a parameter, its logic is only limited to those two scenarios.
function category(String fileName, Bool isWordFile)
This function needs two arguments to categorise a file. The file name and a bool of whether the file is a word file or not.
What happens in the case you need to add an extra possibility? Will you have to do a huge refactor, add an extra parameter, which would be another instance of code smell. It would be better and cleaner to use an enum
instead.
enum FileType {Word, PowerPoint, Excel, Image}
function category(String fileName, FileType fileType)
This way in the case of adding another file type, code change would be minimal and not cause too much code churn.
Vague
Another developer trying to understand your code would see a call like category(fileName, true)
appear somewhere and they would not know what true
represents until they either go to the function definition and inspect it. category(fileName, isWordFile)
is equally unclear. Does it indicate the file is a word file or not?
It’s always good practice to write code that is understood at first glance.
Cohesion
A function should do one thing, and one thing only. The single responsibility principle. Having a boolean as a parameter alters the the logical flow of a function to multiple directions and this will most likely introduce bugs and make it difficult for a refactor. Split the multiple logic into separate functions or have common logic that can be reused. Another good practice to have, code reusability.
function categoriseFiles(String fileName)
— this would be the best way to write this function.
Whenever you find yourself passing a boolean as an argument in your function creation, pause and take a minute to think of a better alternative, because there definitely is!