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

Java 1.8 (3)

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.


Feature Requests: #297


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


Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks