Here is how to refactor (or at least how I refactor, there are other ways) this example I posted earlier.
The class Foo can pretty much be implemented however you want. In
my case, I wanted to get the number of required tokens for a specific
person using an interface. You can see that I created in
interface IPerson that contains GetNumberOfRequiredTokens. This
way I can just pass in an IPerson object type and use the polymorphed,
overriden function in the child class, or adult class (each of which
inherit from the Person class that implements the IPerson
interface). I implemented a property in the base class that
contains the default number of tokens, and then for each derived class,
I use that along with custom calculations the derived class to come up
with the appropriate number of tokens required.
The refactoring pattern we are targeting here is called “conditional
to polymorphism”, along with a few other names. The goal was to
refactor our initial “Select Case” into a base class with derived
classes. This increases usability and scalability greatly over
our initial code we started with.
Don’t forget, and I did not demonstrate this, you will ALWAYS want to write a unit test for your initial code (Foo.GetNumberOfRequiredTokens) and make sure it passes all scenarios BEFORE beginning your refactoring process and DURING and AFTER your refactoring process.
To test this, create a new object of type Adult. Then call
Foo.GetNumberOfRequiredTokens(adultObject) and it will return 3.
