Zahzah
Zahzah

Reputation: 81

Dynamic if-then Code

I'm using Decision Tree algorithm and I get if-then rules (returned as text) for example:

if(Parameter1 > 10) then
   if(Parameter2< 5) then do A
   else do B
else do C

I want to use these rules in order to get decisions for few items: item(Parameter1, Parameter2) example: item1(15, 5), item2(10, 20), ... Problem is, the if-then rules are dynamic and I want to write a code capable of reading this rules and apply them on items.

Upvotes: 0

Views: 235

Answers (1)

Steve Chaloner
Steve Chaloner

Reputation: 8202

You can flip this around and use Predicates to implement your tests. For example,

public class GreaterThan implements Predicate<Integer> {
    private final int point;

    public GreaterThan(final int point) {
        this.point = point;
    }

    public boolean test(final Integer incoming) {
        return incoming > point;
    }
}

and

public class LessThan implements Predicate<Integer> {
  private final int point;

  public LessThan(final int point) {
      this.point = point;
  }

  public boolean test(final Integer incoming) {
    return incoming < point;
  }
}

And so on. You can then use this to dynamically construct logical checks because your tests are now functional.

Predicate<Integer> gt10 = new GreaterThan(10);
Predicate<Integer> lt5 = new LessThan(5);

if(gt10.test(Parameter1)) then
    if(lt5.test(Parameter2)) then do A
    else do B
else do C

Wrap the execution of A, B and C in functions and you're on your way to a flexible system. Now you're dealing with functional objects, you can structure things dynamically - instead of the fixed test shown above, you can compose tests and consequences as required.

Upvotes: 2

Related Questions