5 ms·
It actually feels more like taking an antipattern (switching like in their example produces terrible code in the long run) and turning it into a language featur
by debacle 10y ago
It actually feels more like taking an antipattern (switching like in their example produces terrible code in the long run) and turning it into a language feature.
- barrkel 10y agoIt doesn't necessarily lead to terrible code in the long run. It depends on which abstraction axis changes more frequently in your code. Are you familiar with the expression problem? [1] It's a problem that comes up a lot when you have a bunch of algorithms and a bunch of related values in a data structure, and you want to apply the algorithms to the values. If you have a fixed number of algorithms but keep adding new types of values, it makes sense to use virtual methods for the algorithms; if you have a fixed number of types of values, but keep adding new algorithms, it makes sense to use switch statements (ideally with completeness checking), or pattern matching (if available). The second case is where the C# feature is useful, and it does not produce terrible code in the long run. [1] https://en.wikipedia.org/wiki/Expression_problem https://en.wikipedia.org/wiki/Expression_problem
- debacle 10y agoI can't say I agree in any way. There's no instance where a switch statement is preferable to a hash table or pattern matching. If you have a switch with 3 or fewer cases, use if/else. If you have a switch with more cases, a hash table is going to wind up with far less code, and set you up for polymorphism later if you decide you need to go that route.
- svick 10y agoHow do you create a hash table where the value is an action that depends on the type of the value? The best you can do is something like Dictionary<Type, Action<object>> and use casting in the action, but that's much worse than C# 7.0 switch.
- barrkel 10y agoIn the context of the article (C# patterns), I'm talking about switch statements specifically as a kind of pattern matching. I disagree that hash tables will end up with less code; the dispatch mechanism for a hash table will be significantly longer than a switch, and the compiler can create a hash table for dispatch (using e.g. a perfect hash function). A switch statement will both be faster and easier to understand and read than storing lambdas in a hash table. For pure readability, languages with good support for hash literals and lambdas may have the edge, but they'll also encourage dynamism that will hurt both simplicity and performance.