Re: switch using strings
On Wed, 23 Feb 2011, Joshua Cranmer wrote:
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,
Almost always, yes. But not quite always.
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).
That's what i'd usually do. But thinking about it, i don't see why it's
preferable to my hypothetical class switch. What's the benefit? How does
using a visitor rather than a switch help me deliver more value to my
customer?
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).
That has got to be the fastest abandonment of the technical high ground i
have ever seen. Did you use a sledge? :)
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.
It's mostly a contrived example. I mean, we do actually have some logic
almost exactly like that, but we recognise it's a mistake and are working
on getting rid of it!
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.
Duff's device!
tom
--
everything from live chats and the Web, to the COOLEST DISGUSTING
PORNOGRAPHY AND RADICAL MADNESS!!