如何避免在列表迭代期间返回空值(应该是默认结果)?
How to avoid returning null value (which should be default result) during iteration of a list?
我想要一个通过循环迭代的方法,如果满足某些条件则return一个值(在这种情况下为"1"
).如果条件不为真,则默认值为空。在这种情况下 return null
可以吗?最干净的解决方案是什么?
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...) {
return "1";
}
}
}
return null;
好吧,如果只有两种可能性(在你的情况下是 1 或 null),最好的方法是 return a boolean
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...) {
return true;
}
}
}
return false;
如果调用者希望从您的方法中得到某些东西,建议不要 return null。
例如,如果您的方法应该 return 一个字符串,当
什么都找不到只是 return 一个空字符串 ""
或者如果您的函数应该 return 一些东西,
return无效号码-1
如果该方法应该 return 某物的列表,return
空列表。
当您没有可以解释为错误值的东西时,可以 returned。然后 return null
在任何情况下,您都有责任编写文档来解释 return 在这种情况下是什么。调用者有责任检查 returned 对象是否正确
对抗空指针的最干净的解决方案是使用 JDK8 中引入的 Optionals。 http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
使用 java 8
中介绍的 Optional
是一种好方法(返回 true 或 false):
boolean b = containsOne();
if (b) {
// Do something with success...
} else {
// Do something with failure...
}
private boolean containsOne() {
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...) {
return true;
}
}
}
return false;
}
然而,另一种方法是使用 try and catch block which is mentioned in Clean Code:
try {
int i = getOne();
// Do something with success...
} catch (Exception e) {
// Do something with failure...
}
private int getOne() throws Exception {
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...){
return 1;
}
}
}
throw new Exception();
}
我想要一个通过循环迭代的方法,如果满足某些条件则return一个值(在这种情况下为"1"
).如果条件不为真,则默认值为空。在这种情况下 return null
可以吗?最干净的解决方案是什么?
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...) {
return "1";
}
}
}
return null;
好吧,如果只有两种可能性(在你的情况下是 1 或 null),最好的方法是 return a boolean
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...) {
return true;
}
}
}
return false;
如果调用者希望从您的方法中得到某些东西,建议不要 return null。
例如,如果您的方法应该 return 一个字符串,当 什么都找不到只是 return 一个空字符串
""
或者如果您的函数应该 return 一些东西, return无效号码
-1
如果该方法应该 return 某物的列表,return 空列表。
当您没有可以解释为错误值的东西时,可以 returned。然后 return null
在任何情况下,您都有责任编写文档来解释 return 在这种情况下是什么。调用者有责任检查 returned 对象是否正确
对抗空指针的最干净的解决方案是使用 JDK8 中引入的 Optionals。 http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
使用 java 8
中介绍的 Optionalboolean b = containsOne();
if (b) {
// Do something with success...
} else {
// Do something with failure...
}
private boolean containsOne() {
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...) {
return true;
}
}
}
return false;
}
然而,另一种方法是使用 try and catch block which is mentioned in Clean Code:
try {
int i = getOne();
// Do something with success...
} catch (Exception e) {
// Do something with failure...
}
private int getOne() throws Exception {
for (Obj1 obj1 : objects1) {
for (Obj2 obj2 : objects2) {
if (...){
return 1;
}
}
}
throw new Exception();
}