Complex conditional filter design

437 views Asked by At

I'm stuck at implementing some conditional rules in a form in the backend. Basically i need to come up with an efficient and scalable way of doing this. I was looking into binary trees and decision trees for this one but still not sure what's the best way to implement this.

enter image description here

As you can see there's one statement with the possibility of more than one conditions separated by logical AND/OR. Basically what i need to know is the data structure to store this information in the database. It will act as a filter when a form is submitted by the user based on the form values when it goes through the filter some action will take place as a result.

1

There are 1 answers

1
Amir Afghani On

Your question is a bit generic, but let me see if I can help you get started. In Java, you can set up a class structure as follows :

interface ConditionTree {
    boolean evaluate(...);
}

class OperatorNode implements ConditionTree {
   List<ConditionTree> subTrees = ....;

   @Override
   boolean evaluate(...) {
      if(operator == AND) {
      //loop through and evaluate each sub tree and make sure they are all true,
      //or return false
      }
      else if(operator == OR) {
      //loop through and evaluate each sub tree, and make sure at least one is
      //true, or return false
      } 
   }
}

class LeafNode implements ConditionTree { 
    @Override
   boolean evaluate(...) {
      //get the LHS, operator, and RHS, and evaluate them   
   }

}

Notice it's an N-ary tree, not a binary tree.