I reviewed some recent client Classic ASP code and found a 4 level deep branching of an IF statement. Reading the code, its intent is to look at the object type and return an icon representing the type.
<%
if obj.type = "car" then
response.write("<img src="/images/icons/car.png" />")
ElseIf obj.type = "boat" then
response.write("<img src="/images/icons/boat.png" />")
ElseIf obj.type = "bike" then
response.write("<img src="/images/icons/bike.png" />")
Else
response.write("<img src="/images/icons/placeholder.png" />")
%>
I try to stay away from IF statements altogether but using a SINGLE if statement is something I do use. However, once the IF statement gets past 2 branches, I consider this a CODE SMELL it requires refactoring.
I am going to break my thoughts into small code refactorings so you can understand each step. each step in itself is an improvement to the code, but combined, it will help make changes for the client easier and less prone to bugs.
Step 1
Taking a look at the above code, I notice we are repeating the IMAGE SRC path. So let’s see if we can make better.
<%
Dim imgSrc
imgSrc = "/images/icons/"
if obj.type = "car" then
response.write("<img src='" & imgSrc & "car.png" />")
ElseIf obj.type = "boat" then
response.write("<img src='" & imgSrc & "boat.png" />")
ElseIf obj.type = "bike" then
response.write("<img src='" & imgSrc & "bike.png" />")
Else
response.write("<img src='" & imgSrc & "placeholder.png" />")
%>
Step 2
Now, we are still repeating the response.write("
block several times. Let’s refactor the IF statement to only have logic about the obj.type
.
<%
Dim imgSrc, img
imgSrc = "/images/icons/"
img = "placeholder.png"
if obj.type = "car" then img = "car.png"
if obj.type = "boat" then img = "boat.png"
if obj.type = "bike" then img = "bike.png"
response.write("<img src='" & imgSrc & img & "'" />")
%>
Refactoring Results
The code is much easier to read and to maintain. We can easily add more branches without thinking of the rest of the logic. A non-programmer can look at this code and figure out how to add more images or even change the root path to the images.
In the next post, we will extract the IF statements into a Classic ASP Function.
If you are a looking for Classic ASP Experts or upgrading to .NET from Classic ASP , contact us today.