![](/img/trans.png)
[英]How do I use the SSLEngine methods wrap & unwrap with application data?
[英]How do I use methods with optional data
我创建了一个名为Person
的类,它使用Optional<LocalDate>
将一个人的生日存储为一个字段。 我有一个名为timeToNextBirthday
的方法,它计算调用时间和下一个生日之间的时间间隔。 我遇到的问题是,由于生日是可选的,因此该方法有时无法返回任何内容。 我不知道是应该抛出异常还是只返回一些默认对象。 我还考虑过将返回类型设为可选并在生日未知时返回一个空的可选。 到目前为止,这是我使用异常选项的代码片段。
public class Person {
private Optional<LocalDate> dateOfBirth;
public Period timeToNextBirthday() throws NoSuchElementException {
if(!dateOfBirth.isPresent()) {
throw new NoSuchElementException("Birthday is unknown");
}
LocalDate currentDate = LocalDate.now();
// Assume this year's birthday has not passed and set next birthday to this year
LocalDate nextBirthday = dateOfBirth.get().withYear(currentDate.getYear());
// Add a year to nextBirthday if this year's birthday has already passed or is today
if (currentDate.isAfter(nextBirthday) || currentDate.equals(nextBirthday)) {
nextBirthday = nextBirthday.plusYears(1);
}
return Period.between(currentDate, nextBirthday);
}
}
我应该如何进行?
考虑一下:将方法的返回类型更改为Optional<Period>
将使此方法的用户非常清楚,由于dateOfBirth
是可选的,因此它可能不会导致可用的Period
并且必须使用户空间代码适应此事实。
如果您不想抛出异常(就像您目前所做的那样),这种类型的结转就很好,因为它允许您作为 API 设计人员帮助您的代码用户以安全的null
安全覆盖所有基础和自我记录的方式。 当然,写一些 javadoc 来解释为什么返回类型被包裹在Optional
也不会受到伤害:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.