DEV Community

Discussion on: Stop using if else

 
rjitsu profile image
Rishav Jadon

This comment, and example is the best to explain the concept, thanks for this!

Thread Thread
 
naveennamani profile image
naveennamani

@davidlazic are you saying i should replace

a===10
Enter fullscreen mode Exit fullscreen mode


with

example('a', a)
Enter fullscreen mode Exit fullscreen mode


sure those are equivalent, but what above the functionality that i intended to run in the if condition, should I wrap them in anonymous functions and pass to another function. What about the else if condition? Should I call that like

if(example('b', b))

?
If all conditions has some common logic you can use mapping to bring the variability into the object and using the mapped values to execute the logic. But again, even if slight deviation is added (for example a console log in a single else if condition) then your common logic is not common anymore, and you have to add more hacks like anonymous functions as part of the mapping object and so on, as you just demonstrated in your example with validation functions.

The best practical example would be state management in redux, where switch case statements seems to be most efficient, readable and manageable, try implementing that with mapping.

Thread Thread
 
davidlazic profile image
David Lazic

Hey @naveennamani , appreciate the time you've taken to think about this. My comment was a reply, not a statement, where I simply described how a specific problem could be written in a different kind of way with an example. Like I wrote, I use if/else, switch and this kind of approach on every day basis, based on the situation. If a function is supplied with too much logic, there's probably something that's gonna go wrong and it could be split into separate pure parts.

Some comments have been hidden by the post's author - find out more