IMO switch
statements are not bad, but should be avoided if possible. One solution would be to use a Map
where the keys are the commands, and the values Command
objects with an execute()
method. Or a List
if your commands are numeric and have no gaps.
However, usually, you would use switch
statements when implementing design patterns; one example would be to use a Chain of responsibility pattern to handle the commands given any command "id" or "value". (The Strategy pattern was also mentionned.) However, in your case, you might also look into the Command pattern.
Basically, in OOP, you'll try to use other solutions than relying on switch
blocks, which use a procedural programming paradigm. However, when and how to use either is somewhat your decision. I personally often use switch
blocks when using the Factory pattern etc.
A definition of code organisation is :
- a package is a group of classes with coherant API (ex:
Collection
API in many frameworks)
- a class is a set of coherent functionalities (ex: a
Math
class...
- a method is a functionality; it should do one thing and one thing only. (ex: adding an item in a list may require to enlarge that said list, in which case the
add
method will rely on other methods to do that and will not perform that operation itself, because it's not it's contract.)
Therefore, if your switch
statement perform different kinds of operations, you are "violating" that definition; whereas using a design pattern does not as each operation is defined in it's own class (it's own set of functionalities).