什么是在Java中编写两个条件的四种可能性的最佳方法?

huangapple go评论62阅读模式
英文:

what is the best way to write the 4 possibilities of 2 conditions in Java

问题

//Fail 和 // process further 表示相同的代码。

if (CONDITION1 != null && CONDITION2 != null) {
    if (METHOD1()) {
        if (METHOD2()) {
            // 继续处理
        } else {
            // 失败
        }
    } else {
        // 失败
    }
} else if (CONDITION1 != null && CONDITION2 == null) {
    if (METHOD1()) {
        // 继续处理
    } else {
        // 失败
    }
} else if (CONDITION1 == null && CONDITION2 != null) {
    if (METHOD2()) {
        // 继续处理
    } else {
        // 失败
    }
} else { // 两个都为NULL
    // 继续处理
}

有更好的方法来实现吗?

英文:

CONDITION1 AND CONDITION2 are String variables which can be NULL or NON NULL.
Say for example i have 2 variables like CONDITION1 AND CONDITION2.
If CONDITION1 is not NULL, then i call METHOD1() and if it returns TRUE then i check if CONDITION2 is NOT NULL and then i call METHOD2().
If CONDITION1 is NULL, then i check if CONDITION2 is NULL or not. If it is not NULL then i call METHOD2().
If CONDITION1 is NOT NULL, then i call METHOD1() and then i check if CONDITION2 is NULL or not. If it is NULL then i DONT call METHOD2().

BOTH methods return a boolean value. TRUE or FALSE.

  1. If None of them are NULL
  2. If CONDITION1 is NOT NULL and CONDITION2 is NULL
  3. If CONDITION2 is NULL and CONDITION1 is NOT NULL
  4. If both conditions are NULL

Below is the Code using if else if statements.

IS THERE A BETTER WAY TO DO IT ?

//Fail and // process further represent the same code.

       if(CONDITION1 != null && CONDITION2 != null){
			if(METHOD1()){
				if(METHOD2()){
					// process further
				}else{
					//Fail
				}
			}else{
				//Fail
			}
		}else if(CONDITION1 != null && CONDITION2 == null){
			if(METHOD1()){
				// process further
			}else{
				//Fail
			}
		}else if(CONDITION1 == null && CONDITION2 != null){
			if(METHOD2()){
				// process further
			}else{
				//Fail
			}
		}else{//Both are NULL
			// process further
		}

答案1

得分: 7

只要你所有的 // process further 代表相同的代码,以及你所有的 //Fail 代表相同的代码,就像你所说的那样,那么你所做的就相当于:

if ((CONDITION1==null || METHOD1())
    && (CONDITION2==null || METHOD2())) {
    // 进一步处理
} else {
    // 失败
}
英文:

As long as all your // process further represent the same code, and all your //Fail represent the same code, as you say, then what you're doing is the equivalent of:

if ((CONDITION1==null || METHOD1())
    && (CONDITION2==null || METHOD2())) {
    // process further
} else {
    // fail
} 

huangapple
  • 本文由 发表于 2020年7月25日 04:57:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63081373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定