4 ms·
As with everything in programming, it's about tradeoffs. Should you complicate your class hierarchy just to get rid of a lousy if statement? Probably not. Sh
by j_baker 17y ago
As with everything in programming, it's about tradeoffs. Should you complicate your class hierarchy just to get rid of a lousy if statement? Probably not.
Should you make that gigantic switch statement be polymorphic? Definitely. Should you replace repeated if statements with polymorphism? Probably.
Locality of reference is a good thing, but there is a point where you need to break things down in to smaller, more understandable chunks. And if statements are no different.
- dspeyer 17y agoI've always found a good principle to be that functions should do something and classes should be something and it should be possible to explain what that something is in a short sentence. If an if or switch statement can become a map of function pointers or a polymorphic dispatch without violating this principle, go for it. If not, use "if". Even if you have to use a lot of "if", it'll make your code make sense. A related principle is that a function's argument list should never be longer than its body.