英文:
How to use Optional in Java?
问题
我有一个从数据库查询优惠券列表的服务。此服务向客户端返回一个Optional
。
return listOfCoupons.isEmpty() ? Optional.empty() : Optional.of(listOfCoupons.get(listOfCoupons.size() - 1));
而此代码的客户端以以下方式使用名为'coupons'的Optional
:
if (coupons.isPresent) {
save(coupons.get());
}
这个Optional
的使用方式正确吗?
英文:
I have a Service which queries for a list of coupons from the database. This service returns an Optional
to the client.
return listOfCoupons.isEmpty() ? Optional.empty() : Optional.of(listOfCoupons.get(listOfCoupons.size() - 1));
And the client of this code uses Optional
named 'coupons' in the following way:
if (coupons.isPresent) {
save (coupons.get());
}
Is this the correct use of Optional
?
答案1
得分: 5
你使用的 Optional<T>
API 从远处看起来很好,我看不到任何误用。如果我要挑剔并提出建议,我会将以下代码进行修改:
if (coupons.isPresent()) {
save(coupons.get());
}
修改为:
coupons.ifPresent(c -> save(c)); // 或者使用方法引用
不过这实际上取决于个人口味。
英文:
Your use of the Optional<T>
API looks fine from afar as I cannot see any misuse of it. if I were to nitpick and suggest something I would change:
if (coupons.isPresent) {
save (coupons.get());
}
to:
coupons.ifPresent(c -> save(c)); //or method reference
but then again that's down to taste really.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论