Meaningless Drivel is fun!*
The moose likes OO, Patterns, UML and Refactoring and the fly likes Refactoring: Replace Conditional with Polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Refactoring: Replace Conditional with Polymorphism" Watch "Refactoring: Replace Conditional with Polymorphism" New topic
Author

Refactoring: Replace Conditional with Polymorphism

manuel aldana
Ranch Hand

Joined: Dec 29, 2005
Posts: 308
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.


aldana software engineering blog & .more
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
The code you quoted is not the solution, it's the original, unrefactored code. The solution uses polymorphism instead of the switch statement.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
manuel aldana
Ranch Hand

Joined: Dec 29, 2005
Posts: 308
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Refactoring: Replace Conditional with Polymorphism