Re: Long switch statements (and Swing application structural design)
- From: Lew <noone@xxxxxxxxxxxxx>
- Date: Sat, 11 Oct 2008 12:41:16 -0400
John B. Matthews wrote:
In article <hvOdnd8Th9iVNW3VnZ2dnUVZ_g-dnZ2d@xxxxxxxxxxx>,
Lew <noone@xxxxxxxxxxxxx> wrote:
Eric Sosman wrote:RedGrittyBrick wrote:You cannot.In one application I have a long switch statement that looks like thisYou might consider making selectView() an abstract method
// Entity is an enum
private JPanel selectView(Entity entity) {
switch (entity) {
case Country:
return new CountryControl().getJPanel();
case Currency:
return new CurrencyControl().getJPanel();
// and so on, dozens of other similar cases
default:
return null;
}
}
Q1)
I can't help feeling that I ought to be able to find a way to eliminate the switch statement. Ideally one that doesn't just involve transferring complexity elsewhere.
Any ideas?
of Entity, subclassing it appropriately for each instance.
I don't know off-hand whether you can make an `enum' abstract,
Correct, but "You can declare [a] method abstract in the enum type and override it with a concrete method in each constant."
<http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html>
Exactly. Proviso: every constant must provide a concrete implementation.
I found the syntax a little hard to read for many/long concrete methods. Alternatively, the enum's constructor can initialize a reference to an abstract class with a concrete implementation:
<http://sites.google.com/site/drjohnbmatthews/enumerated-functions>
Instead of abstract functions of doubles, could your enum hold abstract GUIs of MVCs?
But you can put behavior in the enum.
entity.getControl().getJPanel();
Any time you find yourself switching or iffing on a type ('instanceof') in order to determine which of several versions of the same method you need, you have subverted polymorphism.
As people are showing, there are idioms besides polymorphism that can work.
Or ones that refactor the polymorphism into interesting places.
You guys have given me a riddle: what are the relative strengths and weaknesses of these idioms?
--
Lew
Why is a raven like a writing desk?
.
- References:
- Long switch statements (and Swing application structural design)
- From: RedGrittyBrick
- Re: Long switch statements (and Swing application structural design)
- From: Eric Sosman
- Re: Long switch statements (and Swing application structural design)
- From: Lew
- Re: Long switch statements (and Swing application structural design)
- From: John B. Matthews
- Long switch statements (and Swing application structural design)
- Prev by Date: Re: What a pity that Java not Include Operators overloading,Wake up
- Next by Date: Re: What a pity that Java not Include Operators overloading,Wake up
- Previous by thread: Re: Long switch statements (and Swing application structural design)
- Next by thread: How to update data inside a text file in Java ?
- Index(es):
Relevant Pages
|