Re: Long switch statements (and Swing application structural design)
- From: "John B. Matthews" <nospam@xxxxxxxxxxxxxx>
- Date: Sat, 11 Oct 2008 11:37:11 -0400
In article <hvOdnd8Th9iVNW3VnZ2dnUVZ_g-dnZ2d@xxxxxxxxxxx>,
Lew <noone@xxxxxxxxxxxxx> wrote:
Eric Sosman wrote:
RedGrittyBrick wrote:
In one application I have a long switch statement that looks like this
// 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?
You might consider making selectView() an abstract method
of Entity, subclassing it appropriately for each instance.
I don't know off-hand whether you can make an `enum' abstract,
You cannot.
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>
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 certainly do it with non-`enum' enums.
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.
--
John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews
.
- Follow-Ups:
- 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
- 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: Storing data periodically on remote server
- Previous by thread: Re: Long switch statements (and Swing application structural design)
- Next by thread: Re: Long switch statements (and Swing application structural design)
- Index(es):
Relevant Pages
|