0
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;
}
4

3 回答 3

3

您需要 if,但您可以重新排列以使其更清晰,符合逻辑组织,遵循以下原则:

  • 早早失败
  • 最小化嵌套
  • 在需要/最小化它们的范围之前不要声明变量

应用上述原则后:

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 变量也只需要在代码中间,所以不需要提前声明它。

于 2013-09-26T05:02:05.297 回答
0

您可以将它们组合起来,如下所示:

if(dateResponse!=null && dateResponse.getDate() !=null)
于 2013-09-26T01:08:35.677 回答
0

考虑到您对这些值返回null时可能发生的情况的反应方式,从调用方法中抛出异常并将异常记录出来也许是一个更好的主意。您也可以将 your 更改dateResponseOptional<GetDate>, 并在它不存在时表现得适当。

考虑:

public Optional<Date> method() {
    Optional<Date> returnValue = Optional.absent();
    Optional<GetDate> dateResponse = client.call();

    if (dateResponse.isPresent()) {
        try {
            Date myDate = dateResponse.getDate();
            returnValue = convertDateToAnotherDate(date); //actual function
        } catch (IllegalStateException e) {
            LOG.error(e);
        }

    } else {
        LOG.error("Service returned no dateResponse");
    }

    return returnValue;
}
  • 我假设client它将返回一个Optional<Date>,如果它存在,我们将表现正常。

  • 我执行正常的业务逻辑,好像威胁null是不可能的。

  • 如果发生错误(我认为是IllegalStateException),我希望我调用的方法会抛出它。
  • 我记录发生的异常,并在构造异常时提供有意义的消息。

的示例结构getDate可能如下所示:

public Date getDate() {
    if(date == null) {
        throw new IllegalStateException("No date present");
    }
    return date;
 }

...现在我们只剩下一个了if

我真的不知道你的变量是什么类型(我的意思是,我真的不知道 - 我问这是否会编译,我有疑问),所以这就是我所能接受的建议。

于 2013-09-26T01:23:04.013 回答