I have seen it written in multiple threads/comments on stackoverflow that using switch is just bad OOP style. Personally I disagree with this.
There will be many cases where you cannot add code (i.e. methods) to enum classes you want to switch on because you don’t control them, perhaps they are in a 3rd-party jar file. There will be other cases where putting the functionality on the enum itself is a bad idea because it violates some separation-of-concerns considerations, or it is actually a function of something else as well as the enumeration.
Last of all, switches are concise and clear:
boolean investable; switch (customer.getCategory()) { case SUB_PRIME: case MID_PRIME: investible = customer.getSavingsAccount().getBalance() > 1e6; break; case PRIME: investible = customer.isCeo(); break; }
I’m not defending every use of switch and I’m not saying it’s always the way to go. But statements like ‘Switch is a code smell’ are just wrong, in my opinion. Does anyone else agree?
Taking your followup:
and one of your comments:
you are right, as far as this goes.
is not the optimal solution for the flexibility you’re talking about. However, the original question didn’t mention the existence of a separate Product base class.
Given the additional information now available, the best solution would appear to be
The investability decision is made (polymorphically!) by the Product, in accordance with your ‘real world’ argument and it also avoids having to make new customer subclasses each time you add a product. The Product can use whatever methods it wants to make that determination based on the Customer’s public interface. I’d still question whether there are appropriate additions which could be made to Customer’s interface to eliminate the need for switch, but it may still be the least of all evils.
In the particular example provided, though, I’d be tempted to do something like:
I find this cleaner and clearer than listing off every possible category in a switch, I suspect it’s more likely to reflect the ‘real world’ thought processes (‘are they below prime?’ vs. ‘are they sub-prime or mid-prime?’), and it avoids having to revisit this code if a SUPER_PRIME designation is added at some point.