英文:
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.
- If None of them are NULL
- If CONDITION1 is NOT NULL and CONDITION2 is NULL
- If CONDITION2 is NULL and CONDITION1 is NOT NULL
- 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论