• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
author and cow tipper
Posts: 5009
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic