Guava Optional as method argument for optional parameters

后端 未结 1 1396
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 14:48

Recently I had a discussion with my teammate on use of Guava Optional for optional parameters in a method.

Let\'s say method is

         


        
相关标签:
1条回答
  • 2020-12-15 15:21

    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).

    0 讨论(0)
提交回复
热议问题