重叠的条件语句重构的Java部分

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

overlapping ifs refactoring of java

问题

String returnStr = "";
if (!a.isEmpty() && !b.isEmpty() && !c.isEmpty()) {
    returnStr = "1";
} else {
    if (!a.isEmpty() && !b.isEmpty()) {
        returnStr = "2";
    } else if (!a.isEmpty() && !c.isEmpty()) {
        returnStr = "3";
    } else if (!b.isEmpty() && !c.isEmpty()) {
        returnStr = "4";
    } else {
        if (!a.isEmpty()) {
            returnStr = "5";
        } else if (!b.isEmpty()) {
            returnStr = "6";
        } else if (!c.isEmpty()) {
            returnStr = "7";
        } else {
            returnStr = "8";
        }
    }
}

return returnStr;
英文:

I'm using java8.
I made the code below from the sample.
I want to refactoring this, but I don't know how.
Let me know if you have any good ideas.

Add Description :
There was some error in coding, so I corrected it.


String returnStr = "";
if(a != "" && b != "" && c != ""){
	returnStr = "1";
}else{
	if(a != "" && b != ""){
		returnStr = "2";
	}else if(a != "" && c != ""){
		returnStr = "3";
	}else if(b != "" && c != ""){
		returnStr = "4";
	}else{
		if(a != ""){
			returnStr = "5";
		}else if(b != ""){
			returnStr = "6";
		}else if(c != ""){
			returnStr = "7";
		}else{
			returnStr = "8";
		}
	}
}

return returnStr;

答案1

得分: 1

从“空”检查中实际暗示的3个位构造一个int

int i = (a != "" ? 4 : 0) | (b != "" ? 2 : 0) | (c != "" ? 1 : 0);

(是的,你应该使用equalsisEmpty(),而不是!=。这不是真正的重点)。

这将得到一个范围在0到7之间的数字。

构造一个包含8个元素的列表或数组,其中数字是您想要返回的值。

然后,使用上面的i来从该列表/数组中选择一个元素:

return list.get(i);  // 或者 array[i]
英文:

Construct an int from the 3 bits effectively implied by the "emptiness" checks:

int i = (a != "" ? 4 : 0) | (b != "" ? 2 : 0) | (c != "" ? 1 : 0);

(Yes, you should be using equals, or isEmpty(), instead of !=. That's not really the point).

This gives a number in the range 0 to 7, inclusive.

Construct an 8-element list or array, where the number is the value you want to return.

Then, use i from above to select an element from that list/array:

return list.get(i);  // or array[i]

答案2

得分: 0

你不需要那些 else,你可以将代码写得更简洁明了,像这样:

if (a != "" && b != "" && c != "") return 1;
if (a != "" && b != "") return 2;
if (a != "" && c != "") return 3;
if (b != "" && c != "") return 4;
if (a != "") return 5;
if (b != "") return 6;
if (c != "") return 7;
return 8;
英文:

You don't need all those else and you could make it more concise and clear like this:

if(a != "" && b != "" && c != "") return 1;
if(a != "" && b != "") return 2;
if(a != "" && c != "") return 3;
if(b != "" && c != "") return 4;
if(a != "") return 5;
if(b != "") return 6;
if(c != "") return 7;
return 8;

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

发表评论

匿名网友

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

确定