1. Overview

Decision constructs are a vital part of any programming language. But we land up in coding a huge number of nested if statements which make our code more complex and difficult to maintain.

In this tutorial, we’ll walk through the various ways of replacing nested if statements.

Let’s explore different options how we can simplify the code.

2. Case Study

Often we encounter a business logic which involves a lot of conditions, and each of them needs different processing. For the sake of a demo, let’s take the example of a Calculator class. We will have a method which takes two numbers and an operator as input and returns the result based on the operation:

public int calculate(int a, int b, String operator) {
    int result = Integer.MIN_VALUE;

    if ("add".equals(operator)) {
        result = a + b;
    } else if ("multiply".equals(operator)) {
        result = a * b;
    } else if ("divide".equals(operator)) {
        result = a / b;
    } else if ("subtract".equals(operator)) {
        result = a - b;
    }
    return result;
}

We can also implement this using switch statements:

public int calculateUsingSwitch(int a, int b, String operator) {
    switch (operator) {
    case "add":
        result = a + b;
        break;
    // other cases    
    }
    return result;
}

In typical development, the if statements may grow much bigger and more complex in nature. Also, the switch statements do not fit well when there are complex conditions.

Another side effect of having nested decision constructs is they become unmanageable. For example, if we need to add a new operator, we have to add a new if statement and implement the operation.

3. Refactoring

Let’s explore the alternate options to replace the complex if statements above into much simpler and manageable code.

3.1. Factory Class

Many times we encounter decision constructs which end up doing the similar operation in each branch. This provides an opportunity to extract a factory method which returns an object of a given type and performs the operation based on the concrete object behavior.

For our example, let’s define an Operation interface which has a single apply method:

public interface Operation {
    int apply(int a, int b);
}

The method takes two number as input and returns the result. Let’s define a class for performing additions:

public class Addition implements Operation {
    @Override
    public int apply(int a, int b) {
        return a + b;
    }
}

We’ll now implement a factory class which returns instances of Operation based on the given operator:

public class OperatorFactory {
    static Map<String, Operation> operationMap = new HashMap<>();
    static {
        operationMap.put("add", new Addition());
        operationMap.put("divide", new Division());
        // more operators
    }

    public static Optional<Operation> getOperation(String operator) {
        return Optional.ofNullable(operationMap.get(operator));
    }
}

Now, in the Calculator class, we can query the factory to get the relevant operation and apply on the source numbers:

public int calculateUsingFactory(int a, int b, String operator) {
    Operation targetOperation = OperatorFactory
      .getOperation(operator)
      .orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
    return targetOperation.apply(a, b);
}

In this example, we have seen how the responsibility is delegated to loosely coupled objects served by a factory class. But there could be chances where the nested if statements are simply shifted to the factory class which defeats our purpose.

Alternatively, we can maintain a repository of objects in a Map which could be queried for a quick lookup. As we have seen OperatorFactory#operationMap serves our purpose. We can also initialize Map at runtime and configure them for lookup.

3.2. Use of Enums

In addition to the use of Map, we can also use Enum to label particular business logic. After that, we can use them either in the nested if statements or switch case statements. Alternatively, we can also use them as a factory of objects and strategize them to perform the related business logic.

That would reduce the number of nested if statements as well and delegate the responsibility to individual Enum values.

Let’s see how we can achieve it. At first, we need to define our Enum:

public enum Operator {
    ADD, MULTIPLY, SUBTRACT, DIVIDE
}

As we can observe, the values are the labels of the different operators which will be used further for calculation. We always have an option to use the values as different conditions in nested if statements or switch cases, but let’s design an alternate way of delegating the logic to the Enum itself.

We’ll define methods for each of the Enum values and do the calculation. For instance:

ADD {
    @Override
    public int apply(int a, int b) {
        return a + b;
    }
},
// other operators

public abstract int apply(int a, int b);

And then in the Calculator class, we can define a method to perform the operation:

public int calculate(int a, int b, Operator operator) {
    return operator.apply(a, b);
}

Now, we can invoke the method by converting the String value to the Operator by using the Operator#valueOf() method:

@Test
public void whenCalculateUsingEnumOperator_thenReturnCorrectResult() {
    Calculator calculator = new Calculator();
    int result = calculator.calculate(3, 4, Operator.valueOf("ADD"));
    assertEquals(7, result);
}

3.3. Command Pattern

In the previous discussion, we have seen the use of factory class to return the instance of the correct business object for the given operator. Later, the business object is used to perform the calculation in the Calculator.

We can also design a Calculator#calculate method to accept a command which can be executed on the inputs. This will be another way of replacing nested if statements.

We’ll first define our Command interface:

public interface Command {
    Integer execute();
}

Next, let’s implement an AddCommand:

public class AddCommand implements Command {
    // Instance variables

    public AddCommand(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer execute() {
        return a + b;
    }
}

Finally, let’s introduce a new method in the Calculator which accepts and execute the Command:

public int calculate(Command command) {
    return command.execute();
}

Next, we can invoke the calculation by instantiating an AddCommand and send it to the Calculator#calculate method:

@Test
public void whenCalculateUsingCommand_thenReturnCorrectResult() {
    Calculator calculator = new Calculator();
    int result = calculator.calculate(new AddCommand(3, 7));
    assertEquals(10, result);
}

3.4. Rule Engine

When we end up writing a large number of nested if statements, each of the conditions depicts a business rule which has to be evaluated for the correct logic to be processed. A rule engine takes such complexity out of the main code. RuleEngine evaluates the Rules and returns the result based on the input.

Let’s walk through an example by designing a simple RuleEngine which processes an Expression through a set of Rules and returns the result from the selected Rule. First, we’ll define a Rule interface:

public interface Rule {
    boolean evaluate(Expression expression);
    Result getResult();
}

Second, let’s implement a RuleEngine:

public class RuleEngine {
    private static List<Rule> rules = new ArrayList<>();

    static {
        rules.add(new AddRule());
    }

    public Result process(Expression expression) {
        Rule rule = rules
          .stream()
          .filter(r -> r.evaluate(expression))
          .findFirst()
          .orElseThrow(() -> new IllegalArgumentException("Expression does not matches any Rule"));
        return rule.getResult();
    }
}

The RuleEngine accepts an Expression object and returns the Result. Now, let’s design the Expression class as a group of two Integer objects with the Operator which will be applied:

public class Expression {
    private Integer x;
    private Integer y;
    private Operator operator;        
}

And finally let’s define a custom AddRule class which evaluates only when the ADD Operation is specified:

public class AddRule implements Rule {
    @Override
    public boolean evaluate(Expression expression) {
        boolean evalResult = false;
        if (expression.getOperator() == Operator.ADD) {
            this.result = expression.getX() + expression.getY();
            evalResult = true;
        }
        return evalResult;
    }    
}

We’ll now invoke the RuleEngine with an Expression:

@Test
public void whenNumbersGivenToRuleEngine_thenReturnCorrectResult() {
    Expression expression = new Expression(5, 5, Operator.ADD);
    RuleEngine engine = new RuleEngine();
    Result result = engine.process(expression);

    assertNotNull(result);
    assertEquals(10, result.getValue());
}

4. Conclusion

In this tutorial, we explored a number of different options to simplify complex code. We also learned how to replace nested if statements by the use of effective design patterns.

As always, we can find the complete source code over the GitHub repository.

 

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.