public void method() {
returnValue = optional.absent();
try {
GetDate dateResponse = client.call();
if (dateResponse != null) {
myDate = dateResponse.getDate();
if (myDate != null) {
returnValue = convertDateToAnotherDate() //actual function
if (!returnValue.isPresent()) {
LOG.error("Missing required fields");
}
} else {
LOG.error("No myDate");
}
} else {
LOG.error("Service returned no dateResponse");
}
} catch (CustomException exception) {
LOG.error("Custom service failed");
}
return retVal;
}
最佳答案
您需要“如果”,但您可以重新排列以使其更加清晰,并按逻辑组织,遵循以下原则:
- 提前失败
- 尽量减少嵌套
- 在需要之前不要声明变量/最小化其范围
应用上述原则后:
public void method() {
try {
GetDate dateResponse = client.call();
if (dateResponse == null) {
LOG.error("Service returned no dateResponse");
return optional.absent();
}
myDate = dateResponse.getDate();
if (myDate == null) {
LOG.error("No myDate");
return optional.absent();
}
returnValue = convertDateToAnotherDate() //actual function
if (returnValue.isPresent())
return returnValue;
LOG.error("Missing required fields");
} catch (CustomException exception) {
LOG.error("Custom service failed");
}
return optional.absent();
}
请注意,现在的测试都是阳性测试(使用 == 而不是 !=,我们的小大脑可以更好地理解)。缩进(嵌套)减少,因此可读性提高。 returnValue 变量也只在代码中间需要,因此无需提前声明。
关于java - 关于如何减少此代码片段中 'if' 语句的数量有什么建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017677/