简体   繁体   中英

Ways to simplify an if-statement in Java

I currently have an if-statement like this:

if (condition1 || condition2) {
     //Do stuff here
     //Small things happened here
     //More stuff

     if (condition1) {
          System.out.println("Thank");
          // Do Task Alpha
          // Do Task Beta
     } else {
          System.out.println("You");
          // Do Task Delta
          // Do Task Gamma
     }
}

So the basic idea is that the if statement happens when either of the conditions is true (In my case, both conditions cannot be true at the same time).

However, once inside the if statement, there is a point where if the first condition is true, print "Thank" and execute Task Alpha and Beta. If the second condition is true, print "you" and execute Task Delta and Gamma. A lot of common statements are executed before we reach this diverging point.

Is this the best/simplest way of writing this whole if statement?

Thanks.

You could use a ternary for the inner if

String toPrint = test == null ? "Thank" : "You";
System.out.println(toPrint);

or even

System.out.println(test == null ? "Thank" : "You");

The best way to write this operation, is exactly like you have in your question. If condition1 is a complex, potentially expensive expression, store its result into a local boolean variable:

final boolean condition1Result = condition1;
if (condition1Result || condition2) {
     //Do stuff here
     //Small things happened here
     //More stuff

     if (condition1Result) {
          System.out.println("Thank");
          // Do Task Alpha
          // Do Task Beta
     } else {
          System.out.println("You");
          // Do Task Delta
          // Do Task Gamma
     }
}

It might be tempting to consider inlining common the code, ie

if(condition1) {
     //Do stuff here
     //Small things happened here
     //More stuff
     System.out.println("Thank");
     // Do Task Alpha
     // Do Task Beta
} else if(condition2) {
     //Do stuff here
     //Small things happened here
     //More stuff
     System.out.println("You");
     // Do Task Delta
     // Do Task Gamma
}

but I wouldn't do it unless the common code is really tiny. The JVM should be capable of doing such optimization at runtime, if beneficial, so you should prefer the variant that avoids code duplication.

If the overall code becomes too complex, consider refactoring the blocks into methods.

if the if-else blocks occur at the end of the wrapping if block - you can move them after the if block:

 if (test == null || testStr.equals("testStr")) {
 //Do stuff here
 //Small things happened here
 //More stuff
 }

 if (test == null) {
      System.out.println("Thank");
 } else if (testStr.equals("testStr")) {
      System.out.println("You");
 }

This way you have only one level of nesting.

Chaining a lot of blocks makes the code more difficult to maintain. One way to avoid these chained blocks is to use return more often to exit the method before reaching the lines of code that don't have to be executed after a condition is met. Check the refactored version of your example below:

private void someMethod(){
    /*If none of the conditions is met, exits without 
    executing any code.*/
    if (!(condition1 || condition2)) {
        return;
    }

    /*Executes code common to any of the two conditions.*/
    //Do stuff here
    //Small things happened here
    //More stuff

    if (condition1) {
        System.out.println("Thank");
        // Do Task Alpha
        // Do Task Beta
        /*After executing the code for the 1st condition,
        exit to avoid the code for the 2nd one to be executed.*/
        return;  
    } 

    /*If the execution reached up to here, then the 2nd
    condition was met and its corresponding code is executed.*/        
    System.out.println("You");
    // Do Task Delta
    // Do Task Gamma
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM