Re: Long switch statements (and Swing application structural design)
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 11 Oct 2008 08:47:06 -0400
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,
but you can certainly do it with non-`enum' enums.
Or you could use a Map<Entity,PanelGetter>, where the
PanelGetter class is subclassed appropriately.
Whether these amount to "transferring complexity elsewhere"
is hard to assess. The decision to use CountryControl in one
place and CurrencyControl in another can't be made to evaporate
altogether, so in that sense complexity is conserved. What it
comes down to, I think, is manageability: Will you find it easier
to deal with `switch' statements, or to manage what might become
a lengthy stretch of initialization code? Chacun à son goût.
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.
- Follow-Ups:
- References:
- Long switch statements (and Swing application structural design)
- From: RedGrittyBrick
- Long switch statements (and Swing application structural design)
- Prev by Date: How to update data inside a text file in Java ?
- Next by Date: Re: How to update data inside a text file in Java ?
- Previous by thread: Long switch statements (and Swing application structural design)
- Next by thread: Re: Long switch statements (and Swing application structural design)
- Index(es):
Relevant Pages
|