Skip to content

Leverage the compiler

B. K. Oxley (binkley) edited this page Aug 14, 2024 · 8 revisions
Gear

Leverage the compiler

Compilers targeting the JVM generally provide warning flags for dodgy code, and a flag to turn warnings into errors: Use them. The compiler is your first line of defense against code issues.

For example, add these flags with javac:

  • -Werror — turn warnings into errors, and fails the build
  • -Xlint:all,-processing — enable all warnings excluding annotation processing

Be judicious in disabling compiler warnings: they usually warn you for good reasons. For javac, disabled warnings might include serial or deprecation.

JVM compilers support -Werror (eg, javac, kotlinc, scalac, et al); enabling/disabling specific warnings may be compiler-specific.

Tips

  • Consider using Error Prone. Error Prone is an excellent compiler plugin to fail problems earlier: fail at compile-time rather than a runtime, however it can be overly strict.
  • Lombok annotation processing fails -Xlint:all. Use -Xlint:all,-processing to bypass warnings about annotation processing. In addition, using Lombok's configuration to add suppression annotations on generated code (so other tools will ignore generated code) needs the older Spotbugs annotations provided as a dependency.

Going further

ErrorProne is an excellent quality-checking tool from Google that extends the standard Java compiler (via compiler plugins), and has optional features to automatically fix problems in code. It is worth time investigating if it is right for your project. Internally, Google uses ErrorProne in Java projects to avoid common coding mistakes and pitfalls.

Clone this wiki locally