0

My categorizer was very simple.

categorize(life) {
   if (life.heart) 
      return animal
   else
      return plant
}

Then life grew complicated and more checks were added

categorize(life) {
   if (life.heart) 
       if (life.onland)
          return landanimal;
       else
          return wateranimal;
   else
      if (life.land )
         return landplant
      else
         return treeplant
}

But stuff did not end there, soon animals became reptiles, mammals, etc. and if-else began to clutter.

What design pattern is suggested to work around this nested if-else complexity?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

1 Answers1

1

This sounds very much like the famous binary decision tree solution to the 20 questions problem. One way of representing your algorithm as data would be to build a binary tree where each node contains a function (or a Strategy instance, same-same) deciding whether to go left or right in the tree.

My answer to a somewhat related problem may also be of interest to you.

Community
  • 1
  • 1
Jonas Kölker
  • 7,680
  • 3
  • 44
  • 51