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?
It's bad OOP style.
Not all problems are best solved with OO. Some you want pattern matching, which switch is the poor man's version of.
Yes, I'm fed up with people telling you it's bad style.
Edit: This made more sense before the question was fixed.
Case statements can almost always be replaced with polymorphism.
This approach will simplify the client code. The client code doesn't have to know the details of how "investibility" is calculated and it no longer has to break the Law of Demeter by digging into the state of the Customer object.
"Also, what if there are new products coming out all the time, each with different investibility decisions and I don't want to be updating my core Customer class every time this happens?"
This springs to mind:
The "problem" with the original use of swtich and adding new types of decisions is that you likely wind up with some huge rats nest of code that is impossible to maintain in a sane way. Splitting the decisions up into classes forces the decision making to be split up. Then, even if you use switch, the code is likely to stay saner and maintainable.