Re: switch using strings
On 02/24/2011 03:57 PM, Tom Anderson wrote:
On Wed, 23 Feb 2011, Joshua Cranmer wrote:
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?
The visitor case is a poor man's implementation of double dispatch (I
meant this earlier when I said "dynamic dispatch"... I suppose 7 PM is
not the time to be rebutting posts...).
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? :)
The real answer to a switch-based-on-class, I think, would be double
dispatch. However, Java doesn't really support double dispatch, and I'm
not sure whether or not it should.
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!
I'll grant you that it is a contrived example, but one would hope that a
contrived example would be more persuasive in explaining why a feature
would be useful...
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!
Hmm, I should put that on a test and ask people what it does and why it
works. I wonder if the average on that question would be above or below 25%.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth