Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll

my Blog
[prev. Lesson]  advice: Encaspulate Code!
     [next Lesson]  advice: Error Trapping Strategies

Case is better than IF (for readabilty)

Here are two code samples. One is built using IFs and the other with CASE.  I think these drive the point home that readability, speed and code flow is clearer with CASEs.

This is the IF example

   filename=/learn/test/suffixif.asp

<Test Script Below>


<html><head>
<title>suffixif.asp</title>
</head>

<body>
<%
' ok test it
For i = 1 TO 1000
    n = i
    Response.Write n & AddSuffix(n) & ".<BR>" 
NEXT
%>

</body>
</html>
<%
FUNCTION AddSuffix(num)
    temp=right(num,1)
    If temp= 1 Then
            AddSuffix = AddSuffix & "st"
    ElseIf temp = 2 Then
            AddSuffix = AddSuffix & "nd"
    ElseIf temp = 3 Then
            AddSuffix = AddSuffix & "rd"
    ElseIf temp<11 Then
        AddSuffix = AddSuffix & "th"
    End If
END FUNCTION
%>

This is the CASE example:

   filename=/learn/test/suffixcase.asp

<Test Script Below>


<html><head>
<title>suffixcase.asp by Dwaine Maltais rmaltais@wilmington.net</title>
</head>

<body>
<%
' ok test it
FOR i = 1 TO 1000
    n = i
    Response.Write AddSuffix(n) & "<br>"
NEXT
%>

</body>
</html>
<%
Function AddSuffix(num)
    numpart = RIGHT(num,1)
    SELECT CASE numpart
    CASE "1"
        IF InStr(num,"11") THEN
            num = num & "th"
        ELSE
            num = num & "st"
        END IF
    CASE "2"
        IF InStr(num,"12") THEN
            num = num & "th"
        ELSE
            num = num & "nd"
        END IF
    CASE "3"
        IF InStr(num,"13") THEN
            num = num & "th"
        ELSE
            num = num & "rd"
        END IF
    CASE "4"
        num = num & "th"
    CASE ELSE
        num = num & "th"
    END SELECT
    AddSuffix = num
END FUNCTION
%>

Chaz Wish List
Tall Tip $5
Grande Tip $20
Venti Tip $39
Tip Jar Thanks
2004 Thanks
2005 Thanks
HUGE Tip -love site