Re: switch using strings
On 02/23/2011 01:54 PM, Tom Anderson wrote:
This would usually be something which would be better handled by
polymorphism, but there are times when you can't do that. There would be
a definite risk that introducing it would lure people away from
polymorphism.
I think if you want to switch on a Class object, you are highly likely
to have a wrong design, since per-class details are being used not in
the definition of the classes. The logic should either be in the classes
themselves, or you should have a neater pattern to access the classes.
If the classes are logically related, you probably ought to do a visitor
pattern (e.g., source code ASTs). In the case of String v. double v.
<something>, handling data internally as a type-tagged system would
allow you to use polymorphism to suit your needs. In the worst case, you
could always use a reflection-based approach to implement true dynamic
dispatch (ew, maybe invokedynamic would neatify that).
It would be particularly nice if the compiler (or IDE, or PMD/FindBugs)
was able to give you a warning when you were missing a case for a
possible subclass. So for:
Payment p;
switch (pg.getClass()) {
case CreditCard: authorizeCreditCard((CreditCard)p); break;
case GiftVoucher: redeemGiftVoucher((GiftVoucher)p); break;
}
It could warn you that you'd forgotten about paying with loyalty points.
Without knowing anything else about that system... that seems horribly
ill-designed.
switch(i) {
case 1: doSomething();
case 2: {
doSomething();
doSomethingElse();
}
case 3, 4: doSomeOtherThing();
}
How nice of you to include support for the case when two cases go to the
same thing. That is by far my biggest (and I think only?) use of
fall-through in switches.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth