What are the ways to eliminate the use of switch in code?
标签:
design-patterns
相关问题
- Name for a method that has only side effects
- What is a correct approach to manage test data usi
- Can a [GoF]-ConcreteSubject override the notify me
- Can the builder pattern ever be doing too much?
- Carry STRef implicitly in an environment during co
If the switch is there to distinguish between various kinds of objects, you're probably missing some classes to precisely describe those objects, or some virtual methods...
Another vote for if/else. I'm not a huge fan of case or switch statements because there are some people that don't use them. The code is less readable if you use case or switch. Maybe not less readable to you, but to those that have never needed to use the command.
The same goes for object factories.
If/else blocks are a simple construct that everyone gets. There's a few things you can do to make sure that you don't cause problems.
Firstly - Don't try and indent if statements more than a couple of times. If you're finding yourself indenting, then you're doing it wrong.
Is really bad - do this instead.
Optimisation be damned. It doesn't make that much of a difference to the speed of your code.
Secondly, I'm not averse to breaking out of an If Block as long as there are enough breaks statements scattered through the particular code block to make it obvious
EDIT: On Switch and why I think it's hard to grok:
Here's an example of a switch statement...
For me the issue here is that the normal control structures which apply in C like languages have been completely broken. There's a general rule that if you want to place more than one line of code inside a control structure, you use braces or a begin/end statement.
e.g.
For me (and you can correct me if I'm wrong), the Case statement throws this rule out of the window. A conditionally executed block of code is not placed inside a begin/end structure. Because of this, I believe that Case is conceptually different enough to not be used.
Hope that answers your questions.
Well, for one, I didn't know using switch was an anti pattern.
Secondly, switch can always be replaced with if / else if statements.
I think the best way is to use a good Map. Using a dictionary you can map almost any input to some other value/object/function.
your code would look something(psuedo) like this:
Why do you want to? In the hands of a good compiler, a switch statement can be far more efficient than if/else blocks (as well as being easier to read), and only the largest switches are likely to be sped up if they're replaced by any sort of indirect-lookup data structure.