This post originated from an RSS feed registered with .NET Buzz
by Raymond Lewallen.
Original Post: Refactoring pattern quiz number 1 answered
Feed Title: Raymond Lewallen
Feed URL: /error.htm?aspxerrorpath=/blogs/raymond.lewallen/rss.aspx
Feed Description: Patterns and Practices, OOP, .Net and Sql
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.
Refactored: conditional refactored to polymorphism
PublicClass Foo
PublicSharedFunction GetNumberOfRequiredTokens(ByVal person As IPerson) As Int32
Return person.GetNumberOfRequiredTokens()
EndFunction
EndClass
PublicInterface IPerson
Function GetNumberOfRequiredTokens() As Int32
EndInterface
PublicMustInheritClass Person : Implements IPerson
Private baseTokenAmount As Int32 = 1
ProtectedReadOnlyProperty Tokens() As Int32
Get
Return baseTokenAmount
EndGet
EndProperty
PublicMustOverrideFunction GetNumberOfRequiredTokens() As Int32 Implements IPerson.GetNumberOfRequiredTokens
EndClass
PublicClass Child : Inherits Person
PublicOverridesFunction GetNumberOfRequiredTokens() As Int32
ReturnMyBase.Tokens()
EndFunction
EndClass
PublicClass Adult : Inherits Person
PublicOverridesFunction GetNumberOfRequiredTokens() As Int32
ReturnMyBase.Tokens * 3
EndFunction
EndClass
PublicClass Infant : Inherits Person
PublicOverridesFunction GetNumberOfRequiredTokens() As Int32