Home
Do you avoid logic errors by using Else If?
  v1.0 Posted at 26/04/2018 3:48 AM by Tiago Araujo
We see a lot of programmers doing this, they have two conditions - true and false - and they do not consider other possibilities - e.g. an empty string. Take a look at this example. We have an If statement that checks what backend database is being used. This is being stored as a property - Backend in config file. At the moment only Access and SQL Server are options.

Private Sub Command0_Click()
If My.MySettings.Default.Backend = "Access" Then
'Call this code ie. SQL commands
Else
'Must be SQL Server
'Call this other code ie. Stored Proc
End If
.....processing code
End Sub

Figure: Bad example with If statement

Consider later on this code is updated... the programmer wishes to add an Oracle backend database option. So they modify the Backend property to include Oracle...

By using the above code, the wrong code will run because the above code assumes two possible situations. To avoid this problem, change the code to be defensive .g. Use an Else If statement (like below).

The user will then get a Logic Error and can report it to the programmer.​

Private Sub Command0_Click()
If My.MySettings.Default.Backend = "Access" Then
'Call this code ie. SQL
ElseIf My.MySettings.Default.Backend = "SQL Server" Then
'Call this other code ie. Stored Proc
Else
Throw New Exception( "Logic Error -- BackEnd is: "
& My.MySettings.Default.Backend)
End If
End Sub

Figure: Good example with If statement


When writing code to trap Logic Errors, use "Select Case" or "switch" statements to enhance readability. e.g. in VB.NET

Private Sub Command0_Click()
Select Case mDataset.Tables(0).Rows(0)("Key")
Case "1"
' Initialize the column list
strTempColumn = ""
Case "2"
' Ignore
End Select
.....processing code
End Sub

Figure: Bad example with Case statement in VB.NET

Private Sub Command0_Click()
Select Case mDataset.Tables(0).Rows(0)("Key")
Case "1"
' Initialize the column list
strTempColumn = ""
Case "2"
' IgnoreCase Else
Throw New Exception("Logic Error")
End Select
.....processing code
End Sub

Figure: Good example - Use 'Select Case' or 'Switch' statements to enhance readability when coding to find logic errors

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.