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"
Then
Call doSendFAX()
ElseIf sChoice = "SMS" Then
Call doSendSMS()
ElseIf sChoice = "MMS" Then
Call doSendMMS()
ElseIf sChoice = "Print" Then
Call doPrint()
Else
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,

ActionEmail
ActionFAX
ActionSMS
ActionMMS
ActionPrint
ActionInvalid

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)
pAction.Execute()


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.

Enjoy.

6 comments:

  1. Very helpful, specially for creating menu driven applications.

    Good job, keep it up (Y)

    ReplyDelete
  2. @Mohammed
    Thanks for dropping by,

    Menu driven application will be much easier using this approach,

    Each menu item is a class,

    create an instance of the class and call its method

    ReplyDelete
  3. Nice post. The dropdown list would get user input and the IAction interface would act as the select, switch, or case (pascal) statement.

    With this technique, your event-driven code would look more object-oriented and elegant than when using If ladders, nested ifs and case statements.

    ReplyDelete
  4. @Cody
    Correct and the only cost is extra classes..

    And you can control everything your code is encapsulated into classes instead of modular functions.

    Although not every If can be converted to classes it require some work to unify your conditions into an interface.

    ReplyDelete
  5. I don't like this approach, so many new classes and less clarity(if I'm reading your code, a simple if statement is easier to understand than tracking down 6 classes).

    Plus allowing the code to create objects from dynamic menu text bothers me, what if I modify the menu and add a new entry called Hack, will your code crash while trying to create ActionHack or even worse, I could add my own class called ActionHack to your code and allow execution of my own code(ok now I'm thinking in C mentality, I think .NET is secure against dll injection?)

    ReplyDelete
  6. @Yaseen,

    You may have a point up there.
    As for tracking .NET allows to group these classes so it will be easier to find.

    Thats why I didn't say eliminate if statements from the code, minimizing if statements is actually better sometimes..


    You brought us to a nice subject injection.
    The thing is that you can register a class but My code will run the classes under my project only.

    MyProject.ActionHack

    Unless you can name your project the same as mine.

    Thats dangerous!

    ReplyDelete

Share your thoughts