DEV Community


Discussion on: Reverse switch?

mellen profile image
Matt Ellen • Edited

It is bad. Do not do it.

It is counter intuitive and, from my experience debugging other people's code, the source of bugs.

codinghusi profile image
Gerrit Weiermann

Well the switch seems more readable than the if else ^^

mellen profile image
Matt Ellen

It is difficult to maintain, far more so than an if statement. This is primarily because it breaks convention, i.e. surprises are bad, and also because the structure is not suited to keeping track of which thing you want to be true.

If you are having this much trouble with if statements, then I would recommend looking at refactoring them into a clearer flow, not misusing switch syntax.

Thread Thread
mangoduck profile image
mangoduck • Edited

So much opinion. If something works, reliably, it's no misuse. Heck, use nothing but lambdas if you want, if it does the job how you want. (You could make a religion outta that...) If it feels contrived then maybe that's just not the place, but when you do find the place, it's beautiful, intuitive, and trivial to maintain.

You know exactly what's going to happen. Every expression will be evaluated in order until one matches, in this case, true, just like conditionals. Unlike conditionals though it doesn't have to be true, could be 3, another expression, function calls that return success or status, etc. Don't forget you have the option of not breaking as well. Lots of neat stuff is possible.

Forem Open with the Forem app