Skip to content

annotation spec

Kengo TODA edited this page Nov 6, 2017 · 2 revisions

WIP for spotbugs 4.0.0. This content is just idea for now.

Order to resolve annotation

TBU: how to handle interface, super class, package? We need to care not only class's package but also its super classes and/or interfaces' one.

@TypeQualifier

@TypeQualifierDefault

@TypeQualifierValidator

@TypeQualifierNickname

@RegEx

@CheckForSigned

@Detained

@Tainted

@Nullable

@CheckReturnValue

This @CheckReturnValue annotation lets method provider to mark their methods, to recommend its users to check returned value. SpotBugs warns if returned value is not used.

Feature

  • @CheckReturnValue can annotate package, then SpotBugs treats that all methods and constructors in this package are annotated with it.
  • @CheckReturnValue can annotate class/interface, then SpotBugs treats that all methods and constructors in this class/interface are annotated with it.
  • User can use @CheckReturnValue(when = When.NEVER) to overwrite existing configuration in package, super class and/or interface.
  • This annotation handles nothing about nullness of returned value.
  • RetentionPolicy of this annotation is CLASS

Expected usage

  • method which uses returned value to represent error, such as java.io.File#mkdir
  • legacy class which handles resources but does not implement AutoCloseable
  • builder, method chain, fluent interface

Related features

  • To ask method users to check nullness of returned value, use java.util.Optional or @CheckForNull.
  • To ensure that returned AutoCloseable instance is closed certainly, use @WillClose and @WillCloseWhenClosed. @WillNotClose should be replaced with @WillClose(when = When.NEVER).

Example

@CheckReturnValue
boolean foo() {
  return false;
}

void main() {
  foo(); // BAD: returned value is ignored
  boolean result = foo(); // BAD: stored to local variable but not used
  if (foo()) { // GOOD: returned value is checked
    ... 
  }
}

References

Legacy implementation

@WillClose

@WillCloseWhenClosed

Dropped annotations

  • @CleanupObligation, @CreatesObligation ... use AutoCloseable instead
  • @DefaultAnnotation, @DefaultAnnotationForFields, @DefaultAnnotationForMethods and @DefaultAnnotationForParameters ... use @TypeQualifierDefault instead
  • @Confidence
  • @CheckForNull ... use @Nullable instead