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?

Read more

Stay Gold, America

We are at an unprecedented point in American history, and I'm concerned we may lose sight of the American Dream.

By Jeff Atwood · · Comments

The Great Filter Comes For Us All

With a 13 billion year head start on evolution, why haven't any other forms of life in the universe contacted us by now? (Arrival is a fantastic movie. Watch it, but don't stop there - read the Story of Your Life novella it was based on

By Jeff Atwood · · Comments

I Fight For The Users

If you haven't been able to keep up with my blistering pace of one blog post per year, I don't blame you. There's a lot going on right now. It's a busy time. But let's pause and take a moment

By Jeff Atwood · · Comments

The 2030 Self-Driving Car Bet

It's my honor to announce that John Carmack and I have initiated a friendly bet of $10,000* to the 501(c)(3) charity of the winner’s choice: By January 1st, 2030, completely autonomous self-driving cars meeting SAE J3016 level 5 will be commercially available for passenger

By Jeff Atwood · · Comments