Video in progress

How do you build a strategy for systematically reducing NullPointerExceptions in a large codebase?

Optional alone isn't the answer. You need an agreed default ("everything is non-null, and if something can be null, it's marked"), annotations like JSpecify, NullAway/Error Prone to check them at build time, and explicit validation at the boundaries (DTOs, the DB, external APIs).

📖 Answer

NPEs are usually born not inside the code but at the boundaries: a field didn't arrive in the JSON, a DB column is nullable, an external library returned null. The strategy has to account for that.

  1. Set the default. At the package level, "everything is non-null":
// package-info.java
@NullMarked
package uz.bank.payments;

import org.jspecify.annotations.NullMarked;

Now only the exceptions are marked: @Nullable String middleName. JSpecify 1.0 is the common standard that Spring Framework 7, Guava and others are moving to; if you have a mix of the old javax.annotation.Nullable, JetBrains and Checker annotations, it's time to unify them.

  1. Check it at build time. The annotation does nothing by itself. NullAway (an Error Prone plugin) reports dereferencing a @Nullable value without a check as a compile error. Turn it on step by step: first in new modules, then expand the -XepOpt:NullAway:AnnotatedPackages=... list.

  2. The boundaries.

  • an incoming DTO: Bean Validation (@NotNull), or Objects.requireNonNull in a record's compact constructor;
  • the DB: if a column is NOT NULL, mark the entity the same way; otherwise the code and the schema lie to each other;
  • an external library: a wrapping adapter that turns null into an Optional or a default.
  1. Optional is only for return values. Not as a field, a parameter, or a collection element.

  2. Collections are never null: return an empty list.

  3. Diagnostics. Helpful NPE messages (Cannot invoke "Address.city()" because "user.address" is null) were added in Java 14 and have been on by default since Java 15; check that this message is preserved intact in your logs.

How to measure: the number of NPEs in Sentry/logs per module. In the modules where NullAway is on, this number should drop almost to zero, which is the best proof for convincing teams.