Monday, March 23, 2009

Minimize If statments in your code

If you are a programmer you will know how much you hate to see them in your code or how much you hate yourself when you have to read a code stuffed with Ifs.

Someone attempted to save our life. He came and brought another form of If statement and called it Select, " aka Switch in C and Java". It did organize the code to an extent, but still the lines of code are not getting any shorter.

I will propose a way to minimize the number of Ifs in your code.

We use an If most of the time when we want to run a function based on a choice or an option. If this is your choice do this, if that is your choice do that.

Here is a typical ugly if statement.

Dim sChoice As String
'Select from a drop down list
sChoice = cmbOptions.Text
If sChoice = "Email" Then
Call doSendEmail()
ElseIf sChoice = "FAX"
Call doSendFAX()
ElseIf sChoice = "SMS" Then
Call doSendSMS()
ElseIf sChoice = "MMS" Then
Call doSendMMS()
ElseIf sChoice = "Print" Then
Call doPrint()
MsgBox("Invalid choice.")
End If

Create an Interface and call it IAction, write a sub call it Execute

Public Interface IAction
Sub Execute()
End Interface

Now create 6 Classes that implements IAction,


In the execute method write the code for each one
I'll help you with first one

Public Class ActionEmail
Implements IAction

Public Sub Execute() Implements IAction.Execute
Call doSendEmail()
End Sub

End Class

Now go to your main code and write this inside of the if statements

Dim sChoice As String
Dim pAction As IAction
'Select from a drop down list
sChoice = cmbOptions.Text
pAction = CreateObject("YourProject.Action" & sChoice)

That's the new code!

You have all your code separated into maintainable classes and very easily located. And Your main code is much easier to read.