Skip to content

Instantly share code, notes, and snippets.

@motlin
Last active February 24, 2022 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motlin/c80e047323a4464a6fdd92c5ae6d9a16 to your computer and use it in GitHub Desktop.
Save motlin/c80e047323a4464a6fdd92c5ae6d9a16 to your computer and use it in GitHub Desktop.
Thoughts on IntelliJ's @flow analysis and null checking

Thoughts on IntelliJ's @Flow analysis and null checking

IntelliJ has an inspection called Java | Code style issues | Can use bounded wildcard that is helpful for ensuring that parameter types are permissive as they ought to be. In the screenshot below, the Inspection is warning on the usages of INPUT and OUTPUT, and I'm about to select the auto-fix on OUTPUT.

image

IntelliJ has an inspection called Java | Abstraction issues | Type may be weakened which can warn in many locations. Like the previous inspection, it is helpful for ensuring permissive parameter types. Here, inputs could be a Collection instead of a List.

image

IntelliJ already has the ability to infer null annotations. In the screenshots above you can see the grayed out @Nonnull annotation. It doesn't really appear in the text, but if I ran Infer Nullity, IntelliJ would insert the annotation for real.

image

I could imagine similar inspections for suggesting adding @Nullable annotations on generics. I'm imagining what it would be like to apply annotations to an entire library.

  • Apply @NullMarked broadly, probably on packages for speed
  • Apply @Nullable manually in most obvious places, like on the type parameters of interfaces
  • Follow static analysis violations for passing null where it's not yet allowed, like a test that calls Iterate.forEach(null)
  • Finally, follow an inspection that suggests "widening" types, in places where we're not accepting null but only delegate to APIs that do.

IntelliJ runtime assertions

Another relevant and interesting feature of IntelliJ is its ability to add runtime assertions for non-null annotated parameters.

image

I used this feature for a time and found a few things I liked.

  • Adding @Nonnull in code becomes almost equivalent to adding Objects.requireNonNull() and is more concise.
  • I tend to put the annotation in more places than the assertion, so when the assertion fails the stack trace is closer to the problem.

But I eventually stopped using it for a few reasons.

  • It only works in the IDE. Eventually I need to add Objects.requireNonNull() anyway.
  • IntelliJ and the build emit different classfiles to the same location on disk. This causes bytecode analysis tools to raise false alerts on the altered bytecode. I don't really understand why, assuming the generated assertions go inside the annotated methods.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment