繁体   English   中英

简化Java中if语句的方法

[英]Ways to simplify an if-statement in Java

我目前有一个if语句,如下所示:

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
     }
}

因此,基本思想是,当两个条件中的任何一个为真时都会发生if语句(在我的情况下,两个条件不能同时为真)。

但是,一旦进入if语句,就会有一个条件:如果第一个条件为true,则打印“谢谢”并执行Task Alpha和Beta。 如果第二个条件为true,则打印“ you”并执行Task Delta和Gamma。 在达到这个分歧点之前,会执行许多常见的语句。

这是编写整个if语句的最好/最简单的方法吗?

谢谢。

您可以在内部使用三元

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

甚至

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

编写此操作的最佳方法就是完全像您在问题中一样。 如果condition1是一个复杂的,可能昂贵的表达式,请将其结果存储到本地boolean变量中:

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
     }
}

考虑内联通用代码可能很诱人,即

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
}

但除非公共代码是真的很小,我不会去做。 如果有益,JVM应该能够在运行时进行这种优化,因此您应该选择避免代码重复的变体。

如果整个代码变得太复杂,请考虑将这些块重构为方法。

如果if-else语句块出现在包裹的结尾if块-你可以在if块之后移动:

 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");
 }

这样,您只有一层嵌套。

链接很多块会使代码更难维护。 避免这些链接的块的一种方法是在达到条件后不必执行的代码行之前,更频繁地使用return退出方法。 在下面检查示例的重构版本:

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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