public static void main(String[] args) {
String result = replaceStr("jaja");
if (result != null) { //在这里又要判断下非空
int count = 50 + Integer.parseInt(result);
}
}
public static String replaceStr(String tem){
String result;
if (tem == null) {
result = null;
} else {
String substring = tem.substring(0, 1);
result = substring;
}
return result;
}
如上代码,我的疑惑时,当参数tem为空,方法返回null,那岂不是又要在调用
replaceStr
这个方法的地方又要判断次返回值是否为null?那这个代码看上去不是很难看,好多if(**!=null)这样的语句。我想问的是:有没有一种设计,可以只要在一处判断非空,其他地方只要写业务逻辑就行了?
And your question is a bit confusing and I can’t understand what question you want to ask.
First of all, your code is wrong
It should be
if (tem == null)
其次,即使这样改过来还是不够严谨,
tem=""
时else
There is something wrong inside.Again, just judging it as null twice is too much.
Finally, the number of judgments is based on your business logic. Even if the number of judgments is reduced in one place, it still has to be repaid in other places.
If you don’t use null as the return value of the method, you don’t need to detect null. For example, in your example, just return "0".
If you are sure your
term
入参在正常业务场景下必须不能为null
,那么没必要去做null
值得判断,尽早抛出空指针异常
is reasonable.You can reduce non-empty judgments through strict design of business logic, but you still cannot guarantee the distortion caused by maintaining the code. Therefore, for the sake of the robustness of the code, it is better to judge first before use. If the scattered code
str == null || "".equals(str)
is not good-looking, you can use your own packaging tool Or use open source tools, such as apache's StringUtils, etc.Changed your code:
First of all, it is unavoidable to determine the business requirement of non-null, or you can add a default value when designing, and use the default value when the return value is null (the specific situation depends on the current situation when the null value is encountered in the business) How to handle one step, or use the default value, or throw an exception, or terminate execution, etc.).
For the use of default values, you can take a look at guava's MoreObjects#firstNonNull.
Optional in java8 is to solve this problem of null judgment (in fact, judgment is still unavoidable, but it is just a different way to avoid NullPointerException), you can also take a look.
In addition, directly ctrl+c spring's StringUtils#replace method is given to you (for the same reason, you can also refer to apache common's StringUtils. Anyway, there is no shortage of StringUtils in the Java world). You can refer to how others implement it.
Personal approach:
Unless you need to return null, don’t return a null value; don’t pass a null value ["Clean Code" also says this]
If null is not returned, the first way is to throw NPE directly; the second way is to use Optional (this can prevent us from forgetting the !=null check, and at the same time it looks more elegant than everywhere!=)
This code makes no sense