Design Pattern to implement Business Rules with hundreds of if else in java

三世轮回 提交于 2019-12-02 17:35:41

Strategy pattern could be useful here. Please check Replace Conditional Logic with Strategy

bingles

You should check out the Rules Design Pattern http://www.michael-whelan.net/rules-design-pattern/. It looks very similar to the example code you gave and consists of a base interface that defines a method for determining if a rule is satisfied and then various concrete implementations per different rules. As I understand it, your switch statement would turn into some sort of simple loop that just evaluates things until your composition of rules is either satisfied or fails.

interface IRule {
    bool isSatisfied(SomeThing thing);
}

class RuleA: IRule {
    public bool isSatisfied(SomeThing thing) {
        ...
    }
}

class RuleB: IRule {
    ...
}

class RuleC: IRule {
    ...
}

Composition Rules:

class OrRule: IRule {
    private readonly IRule[] rules;

    public OrRule(params IRule[] rules) {
        this.rules = rules;
    }

    public isSatisfied(thing: Thing) {
        return this.rules.Any(r => r.isSatisfied(thing));
    }
}

class AndRule: IRule {
    private readonly IRule[] rules;

    public AndRule(params IRule[] rules) {
        this.rules = rules;
    }

    public isSatisfied(thing: Thing) {
        return this.rules.All(r => r.isSatisfied(thing));
    }
}

// Helpers for AndRule / OrRule

static IRule and(params IRule[] rules) {
    return new AndRule(rules);
}

static IRule or(params IRule[] rules) {
    return new OrRule(rules);
}

Some service method that runs a rule on a thing:

class SomeService {
        public evaluate(IRule rule, Thing thing) {
            return rule.isSatisfied(thing);
        }
    }

Usage:

// Compose a tree of rules
var rule = 
    and (
        new Rule1(),
        or (
            new Rule2(),
            new Rule3()
        )
    );

var thing = new Thing();

new SomeService().evaluate(rule, thing);

This was also answered here: https://softwareengineering.stackexchange.com/questions/323018/business-rules-design-pattern

You can use Command pattern or Factory pattern.

Command pattern can be used to replace cumbersome switch/if blocks which tend to grow indefinitely as you add new options.

public interface Command {
     void exec();
}

public class CommandA() implements Command {

     void exec() {
          // ... 
     }
}
// etc etc

then build a Map<String,Command> object and populate it with Command instances:

commandMap.put("A", new CommandA());
commandMap.put("B", new CommandB());

then you can replace your if/else if chain with:

commandMap.get(value).exec();

In Factory Pattern you include your if/switch in a Factory which takes care of the ugliness and hides the abundance of ifs. Example code for Factory Pattern.

Something that might help is a rules engine like Drools. It's not a design pattern though, so this may not be the answer you're looking for. But IMO, you should consider it. Here's a great article on when you should use a rules engine.

Gabriel Aramburu

A design pattern could help you to make the code more readable or improve its maintainability, but if you really need to evaluate such numbers of conditions, the IF statements cannot be avoided.

I would consider seeing the problem from other point of view (e.g.: do I really need one hundred conditional statements to solve the problem?) and I would try to change or to improve the algorithm.

An Expression Language could provide some help because you could create programmatically a string that represents each IF statement and to evaluate the result using this tool, but you still have to solve the problem related to the execution of the particular logic associated with each condition.

A simple strategy demo with python:

class Context(object):
  def __init__(self, strategy):
    self.strategy = strategy

  def execute(self, num1, num2):
    return self.strategy(num1, num2)

class OperationAdd(object):
  def __call__(self, num1, num2):
    return num1 + num2


class OperationSub(object):
  def __call__(self, num1, num2):
    return num1 - num2


if __name__ == '__main__':
  con = Context(OperationAdd())
  print "10 + 5 =", con.execute(10, 5)

  con = Context(OperationSub())
  print "10 - 5 =", con.execute(10, 5)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!