3 ms·
No, please don't do this. It's "clever" in all the wrong ways. It's not idiomatic use of switch, it's more code and line noise than simple if/else (all the swit
by Sharlin 7y ago
No, please don't do this. It's "clever" in all the wrong ways. It's not idiomatic use of switch, it's more code and line noise than simple if/else (all the switch(true), cases, and breaks are just syntactic salt), and it's not nearly as intuitive what happens if your conditions don't happen to be disjoint (in languages with a C-style switch you can control this to an extent with breaks vs. fallthrough but needless to say it's extremely fragile and confusing).
Even in languages with proper pattern matching it makes no sense to do something like the following instead of if/else:
match x {
x if x < 20 => foo(x),
x if x >= 20 => bar(x),
...
}
Avoiding complex if/else chains is a good idea, but replacing them with the same thing, only spelled differently , is not the way to do it.
- mercer 7y agoWhile I agree switch on true might be an 'abuse' of the switch statement, I'm not sure about the last example. In Elixir, I find myself using: if x do <blah> else <bleh> end only in situations where I'm almost certain I won't end up having more cases, and in practice I tend to limit myself even to conditionals that are short, where I can do: if x, do: y, else: z But in many, many situations I go for: case x do <condition 1> -> <stuff> <condition 2> -> <other stuff> end because it looks cleaner, and because I often end up adding another condition. Furthermore, there's also 'cond', which looks similar. using 'case' and 'cond' often just seems clearer to me over having a quite different syntax in the one situation where there's only two options ('if'). (not having to 'break' makes a big difference though)
- UweSchmidt 7y agoWhat is the way to do it? I like having functions with expressive names to encapsulate/hide complexity, and to comment what I'm doing. If it is not obvious why "20" is such a big deal in your code, then that's where I would trip up. I don't mind having a few ifs if they look like this: if (isHoliday()) { } else if (isWeekend()) { }
- Sharlin 7y agoSure. But complex if/else logic, like I said, is often a code smell that indicates that the behavior might be better off abstracted out to a polymorphic entity of whatever sort is idiomatic in your language. There are a lot of "If statement considered harmful" style articles on the web, but I can't seem to find the specific one I had in mind :/