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
Use a language that doesn't come with a built-in switch statement. Perl 5 comes to mind.
Seriously though, why would you want to avoid it? And if you have good reason to avoid it, why not simply avoid it then?
Switch in itself isn't that bad, but if you have lots of "switch" or "if/else" on objects in your methods it may be a sign that your design is a bit "procedural" and that your objects are just value buckets. Move the logic to your objects, invoke a method on your objects and let them decide how to respond instead.
For C++
If you are referring to ie an AbstractFactory I think that a registerCreatorFunc(..) method usually is better than requiring to add a case for each and every "new" statement that is needed. Then letting all classes create and register a creatorFunction(..) which can be easy implemented with a macro (if I dare to mention). I believe this is a common approach many framework do. I first saw it in ET++ and I think many frameworks that require a DECL and IMPL macro uses it.
I think that what you are looking for is the Strategy Pattern.
This can be implemented in a number of ways, which have been mentionned in other answers to this question, such as:
if-else
I refute the premise that switch is inherently bad though.
See the Switch Statements Smell:
Both Refactoring and Refactoring to Patterns have approaches to resolve this.
If your (pseudo) code looks like:
This code violates the Open Closed Principle and is fragile to every new type of action code that comes along. To remedy this you could introduce a 'Command' object:
If your (pseudo) code looks like:
Then you could introduce a 'State' object.
Hope this helps.