Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Refactoring: Replace Conditional with Polymorphism

 
manuel aldana
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

i read through fowler's refactoring: Replace Conditional with Polymorphism.

fowler presents this kind of solution:




but why isn't fowler going even further and uses 'instanceof':



to me the latter code is a better solution. does anybody know why fowler is not going for the more typesafe 'instanceof'? he must have had a reason...

thank you.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code you quoted is not the solution, it's the original, unrefactored code. The solution uses polymorphism instead of the switch statement.
 
manuel aldana
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops,

i got a bit confused (because i read some lines not properly). it makes sense now.
of course payAmount() gets declared abstract in the superclass, subclasses implement it and switch statement gets kicked out.

thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic