• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
santiago martin alfageme
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
santiago martin alfageme
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic