Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Your codebase mixes null returns, Optional, empty collections and exceptions for missing values, causing frequent NPEs. What conventions and tooling would you introduce for a large service?

I would introduce a short set of conventions: never return null for collections or arrays, return Optional for lookups that may find nothing, and avoid Optional in fields, parameters and collections. I would make non-null the default with JSpecify's @NullMarked on every package, mark exceptions with @Nullable, and enforce it in the build with NullAway. Values are validated at the boundaries, with Bean Validation on requests and NOT NULL in the schema, so the core can assume non-null, and the rollout goes package by package while NPE counts in production show progress.

Why this question is asked

When one method returns null, the next returns Optional, a third returns an empty list and a fourth throws, every caller has to read the implementation to know what to expect, and every wrong guess is a potential NullPointerException. In a large service with many contributors this produces a steady stream of production NPEs. Interviewers ask this design question because the answer combines judgement, which convention for which case, with tooling that makes the conventions stick. In this answer, we will define the conventions and the reason for each, add nullness annotations and build-time checking, push validation to the boundaries, and plan an incremental rollout with a way to measure it.

1Why Mixed Conventions Cause NPEs

The root problem is that in plain Java, a reference type says nothing about whether it may be null. A method declared as Customer find(String id) might return null, might throw, or might never fail; the signature looks the same. So callers rely on memory and reading code, and in a large codebase that fails regularly. Each convention we introduce moves some of that knowledge into the type or into a rule the tools can check, so it no longer depends on memory.

2The Conventions

First, collections and arrays are never null. A method returning a List returns an empty list when there is nothing, and fields holding collections are initialised. The reason is that callers almost always iterate, and an empty list makes the loop simply do nothing, with no special case.

Second, a lookup that may find nothing returns Optional. findByEmail returns Optional<Customer>, which tells the caller in the signature that absence is possible and offers orElse, orElseThrow and map to handle it. A method that is expected to always find its result, such as getById for an ID that came from our own database, may instead throw a clear exception when the record is missing.

Third, Optional is for return values only. Optional fields add an object per instance and are not serializable; Optional parameters force callers to wrap values and can themselves be null; and a List<Optional<X>> is better as a list of only the present values. For fields and parameters that may legitimately be absent, we use @Nullable instead, which the tooling checks.

Java
List<Order> ordersFor(String customerId); // never null: empty list when there are none
Optional<Customer> findByEmail(String email); // absence is a normal result
Customer getById(CustomerId id); // throws CustomerNotFoundException if missing
// Avoid:
Optional<String> middleName; // field: use @Nullable String instead
void send(Optional<String> cc); // parameter: use an overload or @Nullable
List<Optional<Order>> orders; // keep only the present values
Which convention for which case
SituationConventionExample
No elementsempty collection, never nullList.of()
Lookup may find nothingreturn OptionalOptional<Customer> findByEmail(...)
Must exist, missing is a failurethrow a specific exceptiongetById -> CustomerNotFoundException
Field or parameter may be absent@Nullable, checked by NullAway@Nullable String middleName
Everything elsenon-null by default@NullMarked package

3Nullness Annotations and Build-Time Checks

Conventions describe intent; annotations make it visible to tools. JSpecify provides standard annotations, now used by Spring Framework 7 and a growing number of libraries. Putting @NullMarked on a package, in its package-info.java, declares that every type in that package is non-null unless explicitly annotated @Nullable. That means most code needs no annotations at all; only the genuinely nullable places are marked.

NullAway, an Error Prone plugin that runs during javac, then checks each package marked as annotated. It reports an error when code dereferences a @Nullable value without a check, passes a possible null where non-null is expected, or returns null from a method not marked @Nullable. Because it runs in the compiler, it is fast enough for every build and every pull request.

Java
// build.gradle.kts (abbreviated; check plugin versions)
dependencies {
implementation("org.jspecify:jspecify:1.0.0")
errorprone("com.uber.nullaway:nullaway:<version>")
errorprone("com.google.errorprone:error_prone_core:<version>")
}
tasks.withType<JavaCompile>().configureEach {
options.errorprone {
check("NullAway", CheckSeverity.ERROR)
option("NullAway:OnlyNullMarked", "true") // check only packages marked @NullMarked
}
}
// Customer.java in a @NullMarked package
public @Nullable String middleName() { return middleName; }
int n = customer.middleName().length();
// error: [NullAway] dereferenced expression customer.middleName() is @Nullable

Notice the OnlyNullMarked option. It makes NullAway check only packages that have opted in with @NullMarked, which is what makes an incremental rollout possible. Unannotated packages are left alone until their turn comes.

4Validating at the Boundaries

Annotations protect code from itself, but nulls also arrive from outside: JSON requests with missing fields, rows with empty columns, messages from other services. So we validate where data enters, and the core can then rely on non-null values.

For HTTP, Bean Validation annotations such as @NotNull and @NotBlank on request DTOs, with @Valid on the controller parameter, make Spring reject an incomplete request with a 400 before our code runs. For the database, NOT NULL constraints on columns that must have values stop bad data from being stored by any code path, including scripts and other services. For messages, the consumer validates the payload when it is deserialised. Inside the boundary, constructors of domain objects use Objects.requireNonNull for required values, so a null that slips through fails immediately with a clear message.

Step throughWhere nulls are stopped
  1. HTTP and messagesBean Validation on DTOs, payload checks
  2. Domain objectsrequireNonNull in constructors
  3. Core logic@NullMarked packages, checked by NullAway
  4. DatabaseNOT NULL constraints on required columns

4 layers, from the top down. Step through them one at a time.

5Rolling It Out Incrementally

Annotating a large service at once is a big, risky change, so we go package by package. We start with the packages that cause the most NPEs, found from production error data, or with leaf packages that have few dependencies. For each package we add @NullMarked, fix what NullAway reports, which is mostly adding @Nullable to fields and returns that really can be null and fixing the real bugs it finds, and commit. New packages are @NullMarked from the start.

We measure progress two ways. The share of packages marked @NullMarked shows coverage, and the count of NullPointerExceptions in production, from error metrics tagged with the exception type, shows the outcome. In a typical service, the NPE count drops noticeably once the busiest packages are covered, and that number is the best argument for continuing.

6Follow-up questions

Why not use Optional everywhere instead of annotations?

Because Optional is a wrapper object, not a type-system feature. Using it for fields and parameters adds allocation and noise and still allows a null Optional. Annotations cost nothing at runtime, work on fields and parameters, and are checked by tools. Optional remains the right choice for return values where absence is a normal result.

What about Lombok, MapStruct and other generated code?

Generated code may not carry the annotations or may confuse the checker. NullAway can be configured to treat certain generated classes or annotations as unannotated, and newer versions of common code generators are adding JSpecify support. Check your versions, and exclude generated sources from the check if necessary.

How does this interact with JPA entities?

Entities are created by the persistence provider through a no-argument constructor, so their fields are briefly null. A common approach is to keep entities in their own package with @Nullable on fields that can be null, map them to non-null domain objects or DTOs at the repository boundary, and rely on NOT NULL constraints for required columns.

7Conclusion

In this answer, we set conventions that remove guesswork: empty collections instead of null, Optional for lookups that may find nothing and only as a return type, and @Nullable for fields and parameters that may be absent. We made non-null the default with JSpecify's @NullMarked, enforced it with NullAway in the build, validated at the boundaries with Bean Validation and NOT NULL so the core can assume non-null, and rolled it out package by package while tracking NPE counts in production.

What to say in the interviewAbout 90 seconds aloud

Open with

The underlying problem is that in Java the type does not say whether something can be null, so callers guess. I would introduce a few clear conventions. Collections and arrays are never null; methods return an empty collection.

Then, if they want more

Lookups that may find nothing return Optional, and a method where a missing record is a failure throws a specific exception instead. Optional is only for return values, not fields, parameters or collection elements; for those I use @Nullable.

Then tooling: I would put JSpecify's @NullMarked on packages, so everything is non-null by default and only the nullable places are marked, and run NullAway as an Error Prone check in the build, so dereferencing a nullable value without a check or returning null from a non-nullable method fails compilation.

I would validate at the boundaries: Bean Validation like @NotNull and @NotBlank on request DTOs, NOT NULL constraints in the schema, payload checks on consumed messages, and requireNonNull in domain constructors, so the core can assume non-null.

For the rollout, I would use NullAway's option to check only NullMarked packages and go package by package, starting with the ones causing the most NPEs, with new packages marked from day one. I would track the share of packages covered and the NPE count from production error metrics to show the effect.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your codebase mixes null returns, Optional, empty collections and exceptions for missing...": https://scrivio-interview-library.netlify.app/java/exceptions/7c642fd8be/