Making code cleaner by replacing multiple conditionals with a strategy dictionary
When you're on a road with no forks, there's zero chance of taking the wrong path. As the road gains forks, your chances of reaching your destination without getting lost decrease.
The same thing happens when we program. The more conditionals we add, the greater the chance of the code taking the wrong path and producing unintended effects. A function without conditionals is therefore better than one filled with them.
Take a look at the following function (which could also be written using a switch/case statement):
function getCustomFormControl(type){
if(type == 'time') {
return Timepicker;
} else if(['single_option', 'multiple_option'].includes(type)) {
return Select;
} else if(type == 'phone') {
return PhoneInput;
} else if(type == 'date') {
return Datepicker;
} else if(type == 'zip') {
return ZipInput;
} else {
return Input;
}
}
This function presents six possible paths the code could take. If it's already harder for the code to follow, it's certainly harder for the programmer who needs to read this sequence of conditionals while figuring out where to make a change.
This is exactly the kind of situation where a plain object can eliminate those forks and significantly reduce the function’s complexity. Take a look:
function getCustomFormControl(type){
return {
'time': Timepicker,
'single_choice': Select,
'multiple_choice': Select,
'phone': PhoneInput,
'date': Datepicker,
'zip': ZipInput,
}[type] || Input;
}
What this second version does is replace a chain of conditionals with a strategy dictionary indexed by each variation's name. The result is a simple, direct relationship between variation and strategy, drastically reducing the cognitive effort required to connect them.
Learn more: If you enjoyed this tip, you’ll probably like to learn how to reduce data with a shell-pipe-like sequence of operations in JavaScript.