I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

June 20, 2004

The Tyranny of ElseIf


I don't understand it. I've seen this phenomenon over and over in VB.NET, in code from experienced programmers:

        If dt.DayOfWeek = DayOfWeek.Sunday Then
            Return dt
        ElseIf dt.DayOfWeek = DayOfWeek.Monday Then
            Return dt.AddDays(6)
        ElseIf dt.DayOfWeek = DayOfWeek.Tuesday Then
            Return dt.AddDays(5)
        ElseIf dt.DayOfWeek = DayOfWeek.Wednesday Then
            Return dt.AddDays(4)
        ElseIf dt.DayOfWeek = DayOfWeek.Thursday Then
            Return dt.AddDays(3)
        ElseIf dt.DayOfWeek = DayOfWeek.Friday Then
            Return dt.AddDays(2)
        ElseIf dt.DayOfWeek = DayOfWeek.Saturday Then
            Return dt.AddDays(1)
        End If

Why in the world would you express logic this way, instead of the much simpler SELECT CASE statement?

        Select Case dt.DayOfWeek
            Case DayOfWeek.Sunday
                Return dt
            Case DayOfWeek.Monday
                Return dt.AddDays(6)
            Case DayOfWeek.Tuesday
                Return dt.AddDays(5)
            Case DayOfWeek.Wednesday
                Return dt.AddDays(4)
            Case DayOfWeek.Thursday
                Return dt.AddDays(3)
            Case DayOfWeek.Friday
                Return dt.AddDays(2)
            Case DayOfWeek.Saturday
                Return dt.AddDays(1)
        End Select

I mention this because I see it constantly from many different programmers. What gives?

I think the ELSEIF keyword is destructive and, like GOTO, has no good use outside of a very specialized niche. ELSEIF, in my experience, is abused far more than it is used properly. Here's another example from a project I work on:

        If result = DialogResult.Retry Then
            strProjectName = .ProjDetailsPnl.PnlGenInfo.TxtProjectName.Text
        ElseIf result = DialogResult.OK Then
            intNewProjectID = .ProjectID
        End If

I have a very hard time coming up with any valid justification for the use of ELSEIF. 98 times out of 100, SELECT CASE is easier to read and offers the CASE ELSE condition, which encourages developers to handle unknown conditions properly. In the above example, what happens when the dialog returns DialogResult.Cancel?

Posted by Jeff Atwood    View blog reactions

 

« Multiple Monitors and Productivity User-Friendly Exception Handling »

 

Comments

I agree. And from my experience, VB seems to encourage deviant logic flow. I've run across

If Not Foo Then
Else
Console.WriteLine("Baz")
End If

as well as things like

If Foo IsNot Nothing Then
If Foo.Length < 6 Then
Console.WriteLine("Foo must be at least six digits!")
End If
End If

I assume the second case is due to non-shortcircuiting boolean operator evaluation (OrElse/AndAlso don't seem to be very popular), but I have no idea what could have brought about the first. Really sloppy refactoring, perhaps?

DeafByBeheading on February 2, 2007 02:23 PM

Okay, but the code is just going to the next Sunday if today is not already Sunday. Given that, why would you use if-then-else *or* select-case? You can use a simple aritmetic operation: addition.

return dt.AddDays((7 - (int) x.Date.DayOfWeek) % 7)

Yeah, it relies on Sunday having value 0. We can change that for other values of Sunday.

Hugh Brown on April 13, 2007 02:15 PM

Im no .net programmer but I have to agree. My primary language is PHP and I see it all to often. especaily the

If Foo IsNot Nothing Then
If Foo.Length < 6 Then
Console.WriteLine("Foo must be at least six digits!")
End If
End If

when it is much simpler to express it as

if(count($foo) < '6')
{
echo "Foo must be at least six digits!";
}

at least in PHP.

Arron on November 23, 2007 06:40 PM

I was just thinking about which one to use today when I remembered I needed _ranges_, i.e.:

if (x 200) ...
else ...

That, and the really short (2-3 cases, perhaps even 4) are the only times when using a strand of if's can be justified. (And when switch...case is broken like with AS3.0's XML objects)

Another evilness of the elseif keyword is that it makes it harder to realize that 'if...elseif...elseif' constructs are equivalent to a set of nested if's, i.e. 'if...else if...else if'.

aib on December 11, 2007 08:55 PM

Don't forget as well that "select case" is easier for the compiler to refactor into jumps based on a fast to calculate value, rather than forcing a load of comparisons like if statements might. This leads to faster code in some cases... of course a large enough select/case will become ifs and elseifs anyway once the compiler has it in its hands, but there is a middle ground too...

Short story, select/case is good for your compiler, if/elseif is not.

Jheriko on January 7, 2008 08:41 AM







(hear it spoken)


(no HTML)




Content (c) 2008 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.