| Author |
procedural switch - is the switch statement bad object oriented design?
|
santiago martin alfageme
Greenhorn
Joined: Apr 27, 2007
Posts: 9
|
|
First post on list, newbie on Java and just preparing SCJA with Mr. McKenzie's book.
There is a heavy criticism on page 292 about switch statment use, branded as "procedural programmer crack". Wow! it's me.
Mr. Mckenzie suggest a more Object-Oriented use based on passing a value to an object instead of value based behaviour (switch).
But I tried to imagine how to code it. May be a getter method inside the object with if-then-else statments?. At the end, it is not the same?.
Or may different classes with overrided methods (inheritance).
|
Santiago Martin Alfageme
Spain
|
 |
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Joined: Aug 26, 2006
Posts: 4962
|
|
Harsh language indeed.
Here's an example of two switch statments I found:
It's very procedural. You could make it more object oriented and use inheritance and commonality by doing something like this:
Refactoring Switch Statements
From reading the history of the Java language, apparently, the designers didn't want the switch statement in the language at all, as it tends to lead to poor OO. Of course, it's such a strong construct in all other languages that leaving it out would make it appear that something was missing. It has its uses, and isn't always bad. It's just always good to ask yourself, when you start using switches, if there isn't a better, more object oriented approach.
I hope you're enjoying the book!
-Cameron McKenzie
|
Author of Hibernate Made Easy, What is WebSphere???, JSF 2.0 Made Easy and the SCJA Certification Guides
|
 |
santiago martin alfageme
Greenhorn
Joined: Apr 27, 2007
Posts: 9
|
|
Thank you very much for your quick and complete response.
Now I understand why books such as Head First Java only explains switch statement linked with enumerations and pushed into an appendix. Simply try to find "switch" on index, there is no such entry!.
I'll try to practice detoxificacion about switch and yes, I enjoy the read of your book!
|
 |
 |
|
|
subject: procedural switch - is the switch statement bad object oriented design?
|
|
|