[Logo] JavaRanch » JavaRanch Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Associate Certification (SCJA)
 
RSS feed
 
New topic
Author

procedural switch - is the switch statement bad object oriented design?

santiago martin alfageme
Greenhorn

Joined: Apr 27, 2007
Messages: 8

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).

This message was edited 1 time. Last update was at by Cameron Wallace McKenzie


Santiago Martin Alfageme
Spain
Cameron Wallace McKenzie
author and cow tipper
Bartender

Joined: Aug 26, 2006
Messages: 4602

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???, Portlet Programming Made Easy and the SCJA Certification Guides
My Hibernate and JPA Tutorials * My Mock Java Certification Exams * My Online Java Tutorials * My CBT Portlet Tutorials.

santiago martin alfageme
Greenhorn

Joined: Apr 27, 2007
Messages: 8

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!

Santiago Martin Alfageme
Spain
 
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Professional Certification » Associate Certification (SCJA)
 
RSS feed
 
New topic
hibernate profiler