Compile time error good. Type name comparison bad. (Originally Posted 5/26/05)

Technorati Tags: ,,

Here’s a little anti-pattern I’ve seen come up several times in different projects over the years.  Somewhere a project has a piece of code that takes a generic Object is supposed to branch out to different sections depending on the type of that object.  Since you can’t do a switch or Select Case on a type, the code usually ends up looking like this.

Public Sub DoSomething(ByVal Thing As Object)
    Select Case Thing.GetType.Name
        Case "Thing1"
            DoThing1(Thing)
        Case "Thing2"
            DoThing2(Thing)
    End Select
End Sub

The trouble here is that the name of the classes have been hardcoded as strings.  First of all, this means that this code will be doing text comparisons each time it is used.  That’s bad for performance reasons.  Secondly, if the name or namespace of one of these classes were to change, the code would still compile just fine, but would throw an error at run time.  That’s bad because it means the end user is going to see an error that never should have made it to production.  Thirdly, while a switch or Select Case statement may look more elegant in your source code, it still compiles down to a series of if-then-else statements behind the scenes, so the motivation to use the switch or Select Case statement in the first place is flawed.

Next time, try this instead:

Public Sub DoSomething(ByVal Thing As Object)
    If TypeOf Thing Is Thing1 Then
        DoThing1(Thing)
    ElseIf TypeOf Thing Is Thing2 Then
        DoThing2(Thing)
    End If
End Sub

Not only is the direct type comparison faster, but any changes to the name or namespace of the classes Thing1 and Thing2 would result in a compile-time error.  Affected code would never make it out the door and into the customer’s hands.  Of course, a decent set of unit tests would catch this error as well, but it wouldn’t fix the performance problems with text comparisons.

This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s