Are there instances where switch(case) is is a good design choice (except for simplicity) over strategy or similar patterns...
相关问题
- Switch String with Enum variables
- 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?
相关文章
- Should client-server code be written in one “proje
- Algorithm for maximizing coverage of rectangular a
- Is there an existing solution for these particular
- go tutorial select statement
- What is Scope Creep? [closed]
- Builders in Java versus C++?
- “Adapter” or “adaptor”?
- Is copy-and-paste coding ever acceptable?
Use Switches when you're testing on values of primitives. (ie. integers or characters).
Use polymorphism when you are choosing between different types.
Examples : Testing whether a character the user has entered is one of 'a', 'b' or 'c' is a job for a switch.
Testing whether the object you're dealing with is a Dog or Cat is a job for polymorphic dispatch.
In many languages, if you have more complicated values you may not be able to use Switch anyway.
The "strategies" could be created with a switch.
That could be the starting point and from there let the polymorphism do the job.
Other that comes to mind need for extra speed at the cost of flexibility. There are cases.
No, the switch statement is probably only a good design choice in simple situations.
Once you are passed a simple situation switch statements become very painful to keep updating and maintaining. This is part of the reason design patterns came about.
Yes, definitely. Many times your switch is only relevant to a very small part of your overall logic and it would be a mistake to create whole new classes just for this minor effect.
For example, let's say you have a database of words, the user input another word, and you want to find that word in the database but include possible plurals. You might write something like (C++)
Doing this with strategies would be overkill.
First of all, Simplicity often is a good design choice.
I never understood this bias against switch/case. Yes, it can be abused, but that, so can just about every other programming construct.
Switching on a type is usually wrong and probably should be replaced by polymorphism. Switching on other things is usually OK.
For one, readability.