• 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

Why instanceof and the practice of casting with if statements is bad practice?

 
Greenhorn
Posts: 8
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can you tell me why this is not a good way to write code (OCP studyguide page 9):

 
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Better code:



And the Cow class should override the feed() method to do whatever addHay() was going to do in the original code; the Bird class should override the feed() method to do whatever addSeed() was going to do; and so forth.

Not only is this much simpler than the original version, it automatically supports feeding of Cockroach and Capybara and Camel and any other subclass of Animal you might choose to create. The original code ignores the existence of polymorphism, which is one of the foundational features of object-oriented programming whereas this code uses polymorphism and method overriding the way they were meant to be used. Code which ignores the right way to do things and instead uses ugly workarounds which don't even work properly can only be considered bad.

 
Paul Clapham
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One other thing: don't be surprised when you see bad code in books which are preparing you for certification exams. Those books aren't there to teach you how to write good code, they are there to teach you how to understand arbitrary Java code. In real life when you look at somebody else's code there's a real possibility that you may be looking at bad code, and it's your responsibility to understand it regardless.
 
I love a good mentalist. And so does this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic