Monday, June 23, 2014

A technic to eliminate select-case structure

Supposedly I have a base class call Vehicle ( in our case, it would be TransactionBE) and I have a sub class of it call Car and another call Van. you may add another Bus, Truck to the list...

Let's say I have a class call Driver (in our case it would be TransactionBO), inside this class I have an overloaded method call Start, inside the start methods, it does different thing for different type of vehicle.

I have a method call Drive which take Vehicle as parameter.as the name suggests, it drive the vehicle. inside the method, the first step is to get the vehicle started. because the Start method is an overloaded one, what we need to do is to check the type of vehicle and then cast it to respective type and call the start method.



Public Class Vehicle

End Class

Public Class Car
Inherits Vehicle
End Class

Public Class Van
Inherits Vehicle
End Class


Public Function Start(ByVal vehicle As Van)
Return "Van gets started"
End Function

Public Function Start(ByVal vehicle As Car)
Return "Car gets started"
End Function

Public Function Start(ByVal vehicle As Vehicle)
Return "the vehicle gets started"
End Function

Public Function DriveSelectCase(ByVal vehicle As Vehicle)
Select Case True
Case TypeOf vehicle Is Van
Return Start(DirectCast(vehicle, Van))
Case TypeOf vehicle Is Car
Return Start(DirectCast(vehicle, Car))
Case Else
Return Start(vehicle)
End Select
End Function

in this case, I have 3 different classes, in our case, we have about over 10 different sub class of TransactionBE, so our case statement would be longer than what I have here. but you get the point, right?

well, there is a way to replace the select-case structure with one line. this is how you do it:


Public Function Drive(ByVal vehicle As Vehicle)
Return Start(Convert.ChangeType(vehicle, vehicle.GetType()))
End Function


the benefits are as following;

1) write less code, less in most of time means better.
2) it is faster, the code does not need to go through the select case logic
3) as we eliminated the select-case structure, the cyclomatic complexity of the method is reduced. in this case, the cyclomatic complexity of function without Select-case structure is 1 and that of the function with select-case structure is based on how big is the structure , in my example, it is 3.
4) less bug, suppose in DriveSelectCase method, we mismatch the Type name in the code like the following, the compiler does not know, you guessed right, you would get a run time error. while in the new method, this problem is eliminated because you do not need to type the type name twice.

Select Case True
Case TypeOf vehicle Is Van
Return Start(DirectCast(vehicle, Car))
Case TypeOf vehicle Is Car
Return Start(DirectCast(vehicle, Van))
Case Else
Return Start(vehicle)
End Select

No comments:

Post a Comment