Sunday, September 5, 2010

Remove that 'IF'

Recently, I was part of a team helping to acquire new Java resources for my organization. Our goal was to find few senior developers. I was surprised to see very few knew how Java (or OOP) can be used to remove those pesky procedural code specially those IFs and Switch statements.

Most of the time these conditional expressions contain one operand as constant (many time hard-coded value). This hard-coding or use of constant not only reduce understandability but also increase maintenance efforts such as adding, removing or updating a condition.

Example:
A menu controller program to handle File menu action could contain below method

public void performAction (String command)
{

if ("open".equals(command)) //action - "open"
{
//"open" action behavior definition
}
else if ("close".equals(command)) //action - "close"
{
//"close" action behavior definition
}
else if("exit".equals(command)) //action - "exit"
{
//"exit" action behavior definition
}

}

clearly there are maintainability issues, we must change the code if we want to add/ remove any action or if we want to change action behavior.

Solution:
Use of Command Pattern along with any resource resolving method (Map, ServiceLocator, DependencyResolver, etc.) can resolve this situation.

Below is just one of the method

MenuController

public class MenuController{

private Map commandMap;

public void performAction(String command)
{
Command cmdObject = commandMap.get(command);
if (cmdObject == null)
{
throw new CommandNotSupportedException(command + " not supported!");
}
cmdObject.execute();
}

}


Command Interface

public interface Command
{
public void execute();
}

Implementation for menu action "Open"

public class OpenCommand implements Command
{
public void execute()
{
//"open" action behavior definition
}
}

Clearly, as implementation defining the action are decoupled we need not to change controller for any action behavior change also actions can now easily added/ removed from the MenuControl using MenuController's Menu.

Maintainability issue resolved!

No comments: