Raymond Lewallen

Sponsors

The Lounge

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Refactoring pattern quiz number 1

Here is a pattern I'm sure we all see quite a bit. Nothing wrong with it really. Small, clean, simple. However, when you take into context the fact that the following code is part of an entire program used to manage carnival rides, how would you refactor the following code? No need to post code, an explanation will do. I'll post the answer and the code in a little while.  This is one of the more straight-foward and obvious patterns to recognize in the context given.  Those of you new to OOP, it may be harder to see.

Part of a carnival program

 

Public Class Foo

 

    Private baseTokenAmount As Int32 = 1

 

    Public Function GetNumberOfRequiredTokens(ByVal typeOfPerson As PersonType) As Int32

        Select Case typeOfPerson

            Case PersonType.Infant

                Throw New Exception("Too young to ride")

            Case PersonType.Child

                Return baseTokenAmount

            Case PersonType.Adolescent

                Return baseTokenAmount * 2

            Case PersonType.Adult

                Return baseTokenAmount * 3

            Case PersonType.Senior

                Throw New Exception("Too old to ride")

        End Select

 

    End Function

 

    Public Enum PersonType

        Infant

        Child

        Adolescent

        Adult

        Senior

    End Enum

 

End Class

 


Posted 04-25-2005 7:42 PM by Raymond Lewallen

[Advertisement]

Comments

Ben Reichelt wrote re: Refactoring pattern quiz number 1
on 04-25-2005 9:03 PM
I would add an abstract method "GetNumberOfTokens" into a Person base class, and then override that method in each of the different Person subclasses, infant, child, adult, etc. to calculate the appropriate number of required tokens, or throw the proper exception.
Adrian Florea wrote re: Refactoring pattern quiz number 1
on 04-26-2005 2:55 AM
George Lewellen wrote re: Refactoring pattern quiz number 1
on 04-26-2005 5:43 AM
I would refactor this into a conditional logic database table. If needed, it could be two dimensional. If the expected results can be identified into a cause and effect action, this logic can be moved from the program and placed into a database, thus, making the program logic less dependent on change. Just a thought...
Raymond Lewallen wrote Refactoring pattern quiz number 1 answered
on 04-26-2005 11:17 AM
Here is how to refactor this example I posted earlier.  The class Foo can pretty much be implemented...
Patrick Steele's .NET Blog wrote The value of unit testing.
on 05-01-2005 9:20 AM

Add a Comment

(required)  
(optional)
(required)  
Remember Me?