[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Java Tip 68: Learn how to implement the Command pattern in Java - JavaWorld - February 1999
"P.H.Welch" wrote:
> <snip>
>
> AVOIDANCE OF SWITCH STATEMENTS
> ==============================
>
> The article says: `Usage of switch statements during coding is a sign
> of bad design during the design phase of an object-oreiented project'.
>
> Did I miss something? Has there been an article titled: "Switch
> Statements Considered Harmful"?
You missed the "Object Oriented Theology Course" ;-)
It's axiomatic!
There is also the issue that switch statements are inherently not extensible, at
least not in the manner that sub-classing is considered to be.
> This article continues: `Commands
> represent an object-oriented way to support transactions and can
> be used to solve this [switch-statement] design problem'. Well,
> their Command pattern certainly uses lots of Objects so I guess
> that makes it `object-oriented' ... but I'm not at all sure of
> the taken-for-granted assumption: "if it's object-oriented, it must
> be good".
That's always a problem for people. I found Article 68 confusing coz there were
so many little classes of obscure function. Fitting the whole together in my mind
was hard. Had I been able to pour over a long switch statement, I wonder whether
it would have been any easier. Probably, but I'm not sure.
It goes to show that you can do bad design in any language using any paradigm or
design pattern you like! But I was certainly disappointed that the code in the
article was not trivial to assimilate. It didn't encourage me to think: "Oh! this
is such a good idea I'll have to start using it for all my work from now on!"
> Can someone say why switch-statements are bad? Surely, it's not
> a sudden worry about run-time efficiency -- a well-optimised
> switch-statement compiles to a computed goto ... which has linear
> execution time ... the same as following a pointer to find the code??
'Efficiency' is typically not a major concern of users of the object-oriented
approach. But one area where it repeatedly pops up is in object re-use. Designs
are made significantly more complex to overcome the high costs of creating and
deleting objects. A pure OO system doesn't re-use objects and will therefore be
easier to understand and maintain. But keeping some/many of the preciously
expensive objects alive in memory longer makes the program spend less time
creating objects and therefore it runs faster. Take this approach a bit further
and you have a collection of active and passive objects. Now, where have I seen
that before? ;-)
--
Richard Beton B.Sc. C.Phys. M.Inst.P.
Roke Manor Research Limited (http://www.roke.co.uk/)
--------- Standard Disclaimer about my own views etc etc --------
--------- My mail client accepts rich text (HTML) mail --------
Welsh Highland Railway: http://www.whr.co.uk/WHR/WHR.html