javaroutesdesign-decisionsworkflow-engine

How to implement numerous conditions in java other than switch case and if/else?


Need to implement a requirement where the flow of code will be decided based on a lot of cases if implemented using switch case, OR a lot of if/else !

Sample code to be implemented:

if(flag='1')
   Invoke a new route

else If(flag='2')
   Invoke route2
.
.
.
.
else if(flag= 30)
  Invoke route 30

Is there a better approach to write such cases other than if/else statements or switch cases??

Something which is similar to internal implementation of workflow engines like jBPM but i actually cant include the workflow engine as it makes the application heavy!

Any suggestions appreciated!


Solution

  • Here is what I was talking about above.

    
        import java.util.function.*;
    
        public class MethodCalls {
    
           public static void main(String[] args) {
              new MethodCalls().start();
           }
    
           public void start() {
              Map<Integer, Function<Integer, Integer>> callTable = new HashMap<>();
              callTable.put(1, a -> prod(a));
              callTable.put(2, a -> sub(a));
              Random r = new Random();
              r.ints(10, 1, 3).forEach(b -> System.out.println("The answer is "
                    + callTable.get(b).apply(r.nextInt(20) + 20) + "\n"));
           }
    
           public int prod(int v) {
              System.out.println("Multiplying " + v + " by " + 40);
              return v * 40;
           }
    
           public int sub(int v) {
              System.out.println("Subtracting " + 30 + " from " + v);
              return v - 30;
           }
        }
    
    

    This is just a toy but it demonstrates the possibilty of augmenting your switch and/or if/else statements with a call table. You may need several maps to handle different interface types or even declare your own functional interfaces to handle additional arguments. You might even make it more dynamic by incorporating reflection to cast functions during runtime.