Contents
Is it OK to use switch case?
No, switch statements are not generally used wrong. It’s more readable then a long if/else chain, compilers can emit very efficient code if the checked values are reasonably contiguous, and it’s easier to write error-checking compilers that warn you when you forget an alternative.
Why switch is a code smell?
The Switch Statement code smell refers to using switch statements with a type code to get different behavior or data instead of using subclasses and polymorphism. This switch(typeCode) structure is typically spread throughout many methods. This makes the code difficult to extend, and violates the Open-Closed Principle.
Which is a bad switch statement in OOP?
‘Bad’ switch statements are often those switching on object type (or something that could be an object type in another design). In other words hardcoding something that might be better handled by polymorphism. Other kinds of switch statements might well be OK.
How to use an ENUM with switch case in Java?
But you need to have an instance variable, a constructor and getter method to return values. Let us create an enum with 5 constants representing models of 5 different scoters with their prices as values, as shown below −
How to throw an exception in switch statement?
In addition to the advise to throw an exception, if you use gcc, you can use the -Wswitch-enum (and eventually -Werror=switch-enum) which will add a warning (or an error) if a member of you enum doesn’t appear in any case. There may be an equivalent for other compilers but I only use it on gcc.
Is it bad to use switch statement in design pattern?
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). Use commands. Wrap the action in an object and let polymorphism do the switch for you.