Guava Optional as method argument for optional parameters

二次信任 提交于 2019-11-29 00:39:24

What are your suggestions on usage of Optional for this scenario?

Avoid. Avoid. Avoid.

While Optional is a cool alternative to null, in Java you'll always end up with it being a bad addition instead. As Seelenvirtuose wrote, there are three possibilities where you need only two. As JB Nizet wrote, it's best used as a return value, where it reminds the caller of the needed check. As a method argument, it doesn't help anything.

Ideally, an optional argument would be just optional like in

getBooks(String catalogId, String categoryId = null)

which is no valid Java. AFAIK the C++ compiler translates it into two methods

getBooks(String catalogId, String categoryId)
getBooks(String catalogId)

which is what you have to write in Java yourself. Leaving a parameter out is the clearest way of making clear that it's optional. Marking the optional argument as @Nullable is nearly as good. Using a nullability checking tool can help you avoid NPEs (which is the main argument for Optional).

What's important is consistency. Consistency across your classes is in your hands. Consistency with JDK means using null, at least for the foreseeable future (one day JDK 8 Optional may prevail).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!