4 ms·
Using ‘switch’ to match arbitrary logic instead of string or number literals
- aasasd 7y agoThis usage is very annoying. It can match on completely arbitrary conditions while pretending that they're homogeneous like conditions in ‘switch’ are supposed to be. You wouldn't fire up a ‘switch ... case ...’ to check one condition, which is what you do in the “early return” pattern that's a lot better for disparate checks than switches and elses. It also uses syntax that's different from regular C-style “I (command you) {to do stuff}”. All that for very dubious benefit, as in I can't see any. I knew exactly one dude who insisted on writing this way, and he's also the only one I know who supported Putin, so I guess pick your choice.
- Razengan 7y agoThat correlation is hilarious.
- aasasd 7y agoThe guy also liked Microsoft's ecosystem (despite coding for a Linux backend) and drove a Chinese-made SUV. I'm comfortable writing off the `switch` pattern as another one of his idiosyncrasies. It also annoyed everyone who came across his code, just as his political views irked people outside of keyboard-mashing time.
- drbojingle 7y agoIMO, I don't really like it as a switch or the if statements. My issue being the multiple booleans being passed to a single function. I could see it growing to 3, 4, or greater too if more social options were added. I prefer enums. SocialUrl = 'github' // or twitter or w/e return socialConfig[SocialUrl] || defaultSocialConfig or how about: const getConfig = (key, default) => config[key] || default Logic per key value isn't necessary. edit: disregard. Misunderstood the code =)
- masklinn 7y agoThere are no multiple booleans passed to the function, there are actual github and twitter URLs being passed in, and likely integrated into the config objects before being checked for existence.
- drbojingle 7y agoahhhh ok, then I've misunderstood the code, thank you. Disregard :)
- neilwilson 7y agoIt's a fairly common pattern. Essentially it's a slightly cleaner way of doing a multiway conditional rather than if and else. Ruby has it explicitly (case, when, else), and of course functional languages with pattern matching operate like this as a matter of course. A Boolean guard followed by the code to run if the guard is matched.
- Traster 7y agoApparently you would see this commonly in hardware design back in the day because one of the compilers picked this up and mapped it to a look up table in the right way where other expressions might not be picked up correctly. I could easily see the same trick working in a software compiler too.
- yvdriess 7y agoJS's switch is a different beast. The OP's statement doesn't work in C/C++ because its case labels need to be unique. You also would need a large number of case statements before a modern optimizing compiler will decide a switch statement is worth a jump table rather than conditionals.
- archi42 7y agoIn fact, the compiler building a static switch table from non-constant expressions sounds a little bit impossible ;-)
- skrebbel 7y agoCoded the "normal" way, you get this: if(githubUrl) { return config.github; } if(twitterUrl) { return config.twitter; } return { to: '', ... }; IMO this is both clearer and easier on the eyes. Can anyone show me an example of this `switch` pattern that actually makes it better than the obvious if-based version? I mean, given that they're early returns, you don't need any `else` statements. And in situations where you couldn't use early returns, the `switch` pattern would require `break;` statements. That would make that code uglier to the same extent as adding `else`s above. What am I missing?
- jbverschoor 7y agoYeah never really liked switches because of the "breaks". Switch statements are a more like goto, and are more low level. I tend to do: if (xx) { } else if (yy) { } else { // maybe some exception for unhandled value } And to align my ifs: if (false) { } else if (xx) { } else if (yy) { } else { // maybe some exception for unhandled value } But then team members and tooling start to complain about dead code.
- w0utert 7y agoThis style of writing switch statements as long sequences of if-elseif-else makes it very easy to mess up when you add additional clauses. It also does nothing to guarantee the conditions are mutually exclusive, which would make the comparisons order-dependent. Last but not least I would guess the compiler does not have as many options to optimize this kind of code, compared to switch statements (a switch statement can be compiled to either chained jumps, or a jump table, but the if-elseif-else implies there could be order-dependencies and/or side-effects evaluating the conditions), limiting the compiler. This is all reasoning from the perspective of a compiled language of course. But even in Javascript implementing switch-statements as if-elseif-else seems like an anti-pattern to me. >> Switch statements are a more like goto, and are more low level. I know about 'goto considered harmful', but sometimes a simple jump table is just what you need, no need to come up with 'better' ways ;-)
- 7y ago
- bruce_one 7y agoCoffescript uses this technique: https://coffeescript.org/#switch https://coffeescript.org/#switch
- jasode 7y agofyi... recent related (but not a dupe) discussion: https://news.ycombinator.com/item?id=20066628 https://news.ycombinator.com/item?id=20066628
- nyir 7y agoYeah that's been around for some time http://clhs.lisp.se/Body/m_cond.htm http://clhs.lisp.se/Body/m_cond.htm
- majewsky 7y agoIn Golang, a missing switch expression is equivalent to the value `true`, so this shortens further to: switch { ... }
- krylon 7y agoBut in Go, case-values must be constants, right? This would make the trick from the referenced source code impossible, I think. (Whether or not that is a good or a bad thing is a question I am deliberately ignoring.)
- lsaferite 7y agoNot true. Go uses logic expressions in the case statements all the time. And as pointed out above, a switch defaults to checking against true. https://tour.golang.org/flowcontrol/11 https://tour.golang.org/flowcontrol/11
- pikzel 7y agoIn Scala you can do this pretty neatly: url match { case GitHubUrl => config.github case TwitterUrl => config.twitter case _ => defaultUrl }
- dep_b 7y agoKotlin and F# have the same, such a clean pattern.
- UweSchmidt 7y agoThat's a nice source of bugs, if you are too quick to assume what the logic does, or what's being returned from elsewhere and just put it into the switch. I found it helpful to devote another line of code and explicitly handle the outcome of computations or return values (except of course in trivial cases).
- siempreb 7y agoThe fact that it works doesn't mean it's good code. A switch statement should not be used like that IMAO because every developer just like the author is confused by first sight. Readability is an extremely important part of good code. Personally I would prefer somthing like this: return (githubUrl) ? configGithub : (twitterUrl) ? configTwitter : configDefault;
- lsaferite 7y agoI personally find this _way_ less readable at a glance. Every argument you make against using switch statements I would make against doing this as well. When you consider the semantics of the statements, using switch statements for this makes more sense than chaining ternary statements. Chained ternary statements is just a less readable if/else chain. Personally, if one of my guys chained a ternary like this I would immediately fail the PR. IMHO at least.
- dep_b 7y agoI do use patterns like this (Swift code): switch (githubURL, twitterURL) { case (let .some(url), _): return config.github // I prefer GitHub and ignore Twitter case (.none, let .some(url)): return config.twitter // Otherwise I'll see if I have Twitter case (.none, .none): return {} // If I have neither I'll create something new } But the code looks like JS and I think it doesn't support switching on tuples? Bonus in Swift is that the compiler actually deduces that I handled all possible cases. No surprises here. Much better than if/then
- bobbylarrybobby 7y agoThis would probably get messy if you had a large number of URLs to check, and also would be very hard to modify. A bunch of `if` statements that return early would be a lot easier to work with.
- dep_b 7y agoAnd a bunch of `if` statements could get hard to maintain once it turns into a bunch of related compound statements, while it doesn't check for missing combinations compile-time. But I don't think you should call any function outside of constructors with more than three-ish parameters to begin with, so probably you would get a dictionary or list of URL's by the time it grows out of control.
- zwetan 7y agogood case for replace switch with polymorphism
- based2 7y agohttps://en.wikipedia.org/wiki/Pattern_matching https://en.wikipedia.org/wiki/Pattern_matching https://alvinalexander.com/scala/how-to-use-if-then-expressions-guards-in-case-statements-scala https://alvinalexander.com/scala/how-to-use-if-then-expressi...
- aiCeivi9 7y agoSo if both conditions are true is switch using earlier option? Or is the order undefined? I prefer to `switch` over mutually exclusive options.
- sli 7y agoThe order is defined. If you supply an object with both keys, you always get the Github return value.