DEV Community

Discussion on: Reverse switch?

Collapse
 
fjones profile image
FJones • Edited

A good rule of thumb I follow for switch(bool) vs if {} else if {} else {} and restructuring:

  • switch(bool) if only one of the conditions can be true for any input, and there is a clear default case. Good example here is implementing compare/spaceship.
  • if {} else if {} else {} if there is overlap between the conditions and order matters. FizzBuzz says hello.
  • restructure the whole thing if order matters but there is no overlap. This particular case almost always indicates a function that does too much.

This also goes with readability: distinct cases make sense for switch(bool) and actually eliminate having to think about order of operations, if applied consistently like this. Small aside: this of course only applies for immediate(-ish) returns, not for complex behaviour within.