One "truely object oriented" answer would be to define an interface for "Rule" (with condition() and action() methods), create 3 implementations, stuff them into a collection, and then just iterate through them generically as in:

List<Rule> rules = .... ; // your 3 rules initialized here somehow
for(Rule r : rules) {
  if(r.condition()) {
    r.action();
  }
}

This makes a lot more sense if you have 300 rules/conditions rather than just 3.

In Java8, you may want to do this instead, if the rules are CPU-intensive:

rules.parallelStream().filter(Rule::condition).forEach(Rule::action);
Answer from Alex R on Stack Overflow
Top answer
1 of 11
33

One "truely object oriented" answer would be to define an interface for "Rule" (with condition() and action() methods), create 3 implementations, stuff them into a collection, and then just iterate through them generically as in:

List<Rule> rules = .... ; // your 3 rules initialized here somehow
for(Rule r : rules) {
  if(r.condition()) {
    r.action();
  }
}

This makes a lot more sense if you have 300 rules/conditions rather than just 3.

In Java8, you may want to do this instead, if the rules are CPU-intensive:

rules.parallelStream().filter(Rule::condition).forEach(Rule::action);
2 of 11
9

The short answer is yes.

There are a few time you can avoid using if for conditional evluation and branching all together. And they have moments of appropriateness.

  1. Polymorphism, when behavior is dependent on the initial values
  2. Referrenced Assignment, when you know the possible initial values and they have 1 to 1 correlation with the return values. Lists are better than arrays for this, but...

    // Example:  
    if (a==1) { b=2;  }  
    if (a==2) { b=17; }  
    
    // Becomes  
    int fx(2);  // our array of answers  
    fx[0] = 2;   
    fx[1] = 17;  
    b = fx[ a - 1 ];
    
  3. Referrenced Branching, when you know the possible initial values and they have 1 to 1 correlation with the function/branch to use. (example not Java)

    // Example:
    if (a==1) { doSomething1();  }  
    if (a==2) { doSomething2(); }  
    
    // Becomes
    function * fx(2);  // our array or better still, list of functions  
    fx[0] = &doSomething1;   
    fx[1] = &doSomething2;  
    `fx a - 1 ; `
    
  4. Direct boolean assignment.

    We hate:

    if (thisCondition == true) {  
      b = true;  
    } else {  
      b = false;  
    }
    

    Should be:

    b = thisCondition;

🌐
Coderanch
coderanch.com › t › 636191 › java › Alternative-statements-approach
Alternative to if-else statements or better approach (Java in General forum at Coderanch)
July 6, 2014 - Java in General · Goutam reddy · Greenhorn · Posts: 14 · posted 11 years ago · Number of slices to send: Optional 'thank-you' note: Send · There are 3 different user input fields like Text box & Drop downs on the UI. The user can search a table with any of the three input fields or by providing different combinations of input fields to narrow the result set.I have used if else statements to implement my logic using these three fields, but the problem is the code looks very ugly with lot of if-else statements and more over if there is one more field added to the UI then I have to check for more combinations with if else statements.
Discussions

java - Alternative of if-else and switch statements - Stack Overflow
The value of i is represented in the object its no longer a var. but it depends on the type of object. it still contains similar logic to the code the OP has but without the if/else just like the OP asked. :) 2014-04-11T05:32:12.703Z+00:00 ... In Java, this should work.. More on stackoverflow.com
🌐 stackoverflow.com
java - What alternatives are there for if else statements? - Stack Overflow
This is a method within my program and I cannot use a bunch of if-else statements for my code. I need alternatives. More on stackoverflow.com
🌐 stackoverflow.com
java - Quick alternative to lots of if statements - Stack Overflow
I'm beginner at java, and I'm making a simple program where I type in something, and if what I type in matches one of the things on the "database" then it'll print some text. Is there a simpler wa... More on stackoverflow.com
🌐 stackoverflow.com
java - What is the better way to escape from too many if/else-if from the following code snippet? - Software Engineering Stack Exchange
I am trying to write a servlet which does task based on the "action" value passed it to as input. Here is the sample of which public class SampleClass extends HttpServlet { public static void More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
March 6, 2017
🌐
Medium
medium.com › javarevisited › alternative-approaches-to-java-conditional-statements-beyond-if-else-9511b2178a31
Alternative Approaches to Java Conditional Statements: Beyond If-Else | by Borys Nikolenko | Javarevisited | Medium
June 2, 2023 - To improve code readability, you can use the Map or Pair approach combined with Predicates. This approach utilizes a map with a condition (Predicate) as the key and a message-building function (Function) as the value.
🌐
Baeldung
baeldung.com › home › java › how to replace many if statements in java
How to Replace Many if Statements in Java | Baeldung
August 8, 2025 - As we can observe, the values are the labels of the different operators which will be used further for calculation. We always have an option to use the values as different conditions in nested if statements or switch cases, but let’s design an alternate way of delegating the logic to the Enum itself.
🌐
iO Flood
ioflood.com › blog › if-else-java
If-Else Java: Mastering Decision Making in Code
February 20, 2024 - While ‘if-else’ statements are a fundamental part of controlling flow in Java, they aren’t the only tool at your disposal. Another powerful tool is the ‘switch’ statement. The ‘switch’ statement in Java allows you to select one of many code blocks to be executed. It’s a more readable and efficient alternative to the ‘if-else-if’ ladder when dealing with multiple conditions.
🌐
Medium
medium.com › swlh › 5-ways-to-replace-if-else-statements-857c0ff19357
Different Ways to Replace If/Else Statements | The Startup
September 25, 2021 - Nevertheless, If-Else has become the de facto solution for code branching — which does make sense. It’s one of the first things any aspiring developer is taught.
🌐
Coderanch
coderanch.com › t › 571310 › java › Alternative-block
Alternative to if else block (Java in General forum at Coderanch)
Mohamed Sanaulla | My Blog | Author of Java 9 Cookbook | Java 11 Cookbook ... introduce one more return statement in end of the if block, so that you can remove else {} something like this:
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 47170930 › what-alternatives-are-there-for-if-else-statements
java - What alternatives are there for if else statements? - Stack Overflow
, "question",JOptionPane.YES_NO_OPTION); //The following if else statments are still within //the first statement of the first if statement if (newChoice4 == JOptionPane.YES_OPTION){ JOptionPane.showMessageDialog(null,"Chair starts " + "rocking with no one in it"); }else{ JOptionPane.showMessageDialog(null, "You see a child outs" + "ide on a swing and he suddenly vanishes."); } }else if (newChoice10 == JOptionPane.NO_OPTION){ JOptionPane.showMessageDialog(null,"You have chosen not " + "to explore Bedroom 1 and therefore continue " + "into the following room"); } return null; }
Top answer
1 of 7
14

Based on the previous answer, Java allows enums to have properties so you could define a strategy pattern, something like

public enum Action {
    A ( () -> { //Lambda Sintax
        // Do A
       } ), 
    B ( () -> executeB() ), // Lambda with static method
    C (new ExecutorC()) //External Class 

    public Action(Executor e)
        this.executor = e;
    }

    //OPTIONAL DELEGATED METHOD
    public foo execute() {
        return executor.execute();
    }

    // Action Static Method
    private static foo executeB(){
    // Do B
    }
}

Then your Executor (Strategy) would be

public interface Executor {
    foo execute();
}

public class ExecutorC implements Executor {
    public foo execute(){
        // Do C
    }
}

And all your if/else in your doPost method become something like

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String action = req.getParameter("action");
    Action.valueOf(action).execute();
}

This way you could even use lambdas for the executors in the enums.

2 of 7
8

Instead of using reflection, use a dedicated interface.

ie instead of :

      /**
       * Still was not comfortable since i am doing un-necessary checks in one way or the other
       * So tried with [reflection][1] by invoking the action methods
       */
      Map<String, Method> methodMap = new HashMap<String, Method>();

    methodMap.put("action1", SampleClass.class.getMethod("action1"));
    methodMap.put("action2", SampleClass.class.getMethod("action2"));

    methodMap.get(action).invoke(null);  

Use

 public interface ProcessAction{
       public void process(...);
 }

Implements each of them for each actions and then :

 // as attribute
Map<String, ProcessAction> methodMap = new HashMap<String, ProcessAction>();
// now you can add to the map you can either hardcode them in an init function
methodMap.put("action1",action1Process);

// but if you want some more flexibility you should isolate the map in a class dedicated :
// let's say ActionMapper and add them on init : 

public class Action1Manager{
    private static class ProcessAction1 implements ProcessAction{...}

    public Action1Manager(ActionMapper mapper){
       mapper.addNewAction("action1", new ProcessAction1());
    }
}

Of course this solution isn't the lighest, so you may not need to go up to that length.

🌐
Stack Overflow
stackoverflow.com › questions › 61576470 › alternative-for-an-if-then-else-statement
java - Alternative for an if then else statement - Stack Overflow
Can anyone assist me with an alternative to if-then-else statements for control flow? Or advise on a good article? From what I've seen, some use mapping or enums. Trouble I'm having is that I have multiple conditions i.e. if (condition1 && condition2 && condition3)...
🌐
Frankel
blog.frankel.ch › even-more-readable-code-without-if-else
Even more readable code without if-else
December 15, 2019 - Imagine we need to check the value of a letter to return an integer associated with the later. As mentioned in the previous post, an easy alternative to if-else is to create a map, with letters as keys, and integers as values.
🌐
iO Flood
ioflood.com › blog › if-statement-java
Mastering If Statements in Java: Basics and Beyond
February 20, 2024 - Two such alternatives are switch statements and ternary operators. A switch statement can be used instead of a complex if-else chain when you need to select one of many code blocks to be executed.
🌐
Coderanch
coderanch.com › t › 656528 › java › Alternatives-null-checks-statements
Alternatives to null checks in if, else if, else statements? [Solved] (Features new in Java 8 forum at Coderanch)
The above ideas can also be used in a normal sort of if..else if..else structure. Main thing, just don't return nulls. A.J. Côté ... I would recommend against creating dummy objects. For me returning nulls is fine. If you do this all over your code, your application will be much slower. ...
🌐
Quora
quora.com › What-are-the-alternatives-to-if-statements-other-than-switching-it-How-do-I-avoid-using-too-many-if-statements
What are the alternatives to “if statements” other than switching it? How do I avoid using too many “if statements”? - Quora
Answer (1 of 9): You can’t always avoid long if or switch statements. All the other answers have already covered the different syntax alternatives for if statements. With that being said, I think the answer you’re looking for in this question is polymorphism, which I’m surprised nobody ...