Menu

#302 Add "isNull -> get"-rule for Java 1.8's new type Optional

3.x
closed-rejected
5
2017-10-22
2014-06-27
No

Since 1.8 Java has a type Optional which might or might not contain a not-null value. Best practice is to always call isPresent() before calling get() (similar to the annotation CheckForNull).

It would be nice to have a FindBugs-rule which enforces this practice.

@Andrey: I took the liberty to set the milestone and owner according to [feature-requests:#297], by which this ticket is inspired.

Related

Feature Requests: #297

Discussion

  • Andrey Loskutov

    Andrey Loskutov - 2014-06-28
    • Group: 3.0.0 --> 3.x
     
  • Tagir Valeev

    Tagir Valeev - 2014-11-10

    Nicolai, I think it would be nice if you provide a link to some open source project which already extensively uses Optional type, so we can use its codebase for testing. Most of big projects I use to test FindBugs still did not switch to Java 8. I suspect in some cases it's possible to call get() without explicit isPresent(). For example if orElseThrow() was called previously for the same Optional. It would be not very nice to produce many false-positives, so some real code to test with is appreciated.

     
  • Nicolai Parlog

    Nicolai Parlog - 2014-11-10

    Unfortunately I can't help you too much here. My own project LibFX uses Optional but is still rather small (if you want to use it, make sure to use the development branch as there is a lot of code not yet merged to master).

    But I ran into some situations where I had to think about this ticket and pondered the same cases you allude to. There might be some "distance" between 'isPresent' and 'get'. Sometimes you might even check and then call another method before accessing 'get' (although this could be considered bad use of Optional). Another possibility is to create an Optional with 'of' and then then later 'get' the value. This could be the case if you want to return or store the optional instance but want to do something with the value first.

     
  • Andrey Loskutov

    Andrey Loskutov - 2017-10-22
    • Labels: Java 1.8 --> report on spotbugs, Java 1.8
    • Status: open --> closed-rejected
     

Log in to post a comment.