This topic is for the [Replace Conditional with Polymorphism] exercise in the [Refactoring] trail. Post any questions, corrections, or pointers you have to share with other Upcase subscribers.
[Replace Conditional with Polymorphism]: https://exercises.upcase.com/exercises/replace-conditional-with-polymorphism
[Refactoring]: Refactoring Code | Code Refactoring Online Tutorial by thoughtbot
Dear Reader,
I’ve tried implementing my solution to this problem in another way(using factory pattern). One could see my current solution via this link . I’d really appreciate some inputs on the following question pertaining to my solution -
- I see that the featured solution uses a template method pattern. What is a more apt(if there’s one) way to solve this problem? I do see and appreciate how the template method pattern solves this problem but I’d like to know whether or not the factory pattern is suitable to the given problem at hand. If not, please elaborate as to why the factory pattern might not be a good fit here.
Also, just to add, I did read @jferris’ comment to a similar question pertaining to his solution but I wasn’t able to fully comprehend what he meant. It would be great if this could be explained in some more detail.
Thank you.
@jferris’ solution actually changed the external behaviour of PhonePlan
While I realize this is an exercise, I am wondering if the code in the assignment is really a good candidate for “Replace conditional with polymorphism”.
When I implemented this in a way that did not change the method signature, but it involved using the code Object.const_get("#{type.capitalize}Plan")
, which I feel ends up with code that is less clear than the original, especially when there is only one conditional being removed (if there were several conditionals being refactored into methods, this might feel more valuable to me).
From Ruby Science (I only have the free chapter):
• Replace Type Code with Subclasses if the case statement is checking a
type code, such as question type.
• Replace Conditional with Polymorphism when the case statement is
checking the class of an object.
In this case we are being asked to do a combination, which does not seem to leave us with elegant code.
I guess if we accept the change to the signature, then the code from the recommended solutions isn’t smelly.
@Upcase I love this exercise on Polymorphism.
I am only surprised the exercises on refactoring ends here.
I was hoping there would be exercises on Composition. Referring to this series of articles, Building Reusable Object-Oriented Systems: Composition, I believe there should be if possible multiple exercises on composition as it is the preferred way over inheritance. I am really looking forward to this.
Thanks