java - 关于如何减少此代码片段中 'if' 语句的数量有什么建议吗?

标签 java

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/

相关文章:

java - 并行执行线程超时

java - 异常搜索的通用实用程序

在 heroku 上部署 Java 应用程序

java - 将 java 日期反序列化为 Instant

Java Condition 在await() 返回后无法重新获取与其关联的锁(ReentrantLock)

java - Spring JPA 并从@ManyToMany 中删除条目

java - 以自定义格式将当前日期保存到 oracle Db

java - Apache HTTPClient 没有这样的方法 ContentType.create

java - Spring boot 中的父应用程序上下文

java - 如果没有 Maven 构建,则无法更改代码