Time for a nice short article.
As a development team, we were having a bit of a side discussion during our ensemble meeting (mobbing session essentially). There was a method call that took a boolean, and we didn’t have the slightest clue what it did just looking at the code.
This led us to ask a question: are booleans ever helpful in method parameters? For me, the answer is no. An enum can do everything a boolean does, but in a much clearer manner. Take a look at these two pieces of code and decide for yourself:
function myFunc(shouldNotDoSomething = false){
if(!shouldNotDoSomething){
console.log('Doing something!');
}
}
// what is true, what is false???
// hard to expand to more cases
myFunc(true);
myFunc(false);
function myFunc(doOrDoNot = DO){
if(doOrDoNot === DO){
console.log('Doing something!');
}
}
// much clearer, easily expands to new
// cases
myFunc(DO_NOT);
myFunc(DO);
Another option could be to use object destructuring parameters, or named parameters in other languages, but I really think you can’t beat the flexibility of an enum, combined with object destructuring/name parameters (depending on the language). An ideal piece of code might look like this:
// so easy to extend and refactor
function myFunc({
doOrDoNot = DO,
}){
if(doOrDoNot === DO){
console.log('Doing something!');
}
}
// couldn't be more obvious what's
// happening now
myFunc({ doOrDoNot: DO_NOT });
myFunc({ doOrDoNot: DO });
That’s all! These small programming tweaks can really add up if you’re always aiming for best practices, and to code for everyone else’s ease of use and understanding.