說明

Methods that return Optional<T> must never return null. Methods that return nullable references must be annotated with @Nullable.

The goal is to eliminate NullPointerExceptions at their source.

為什麼重要

NPE is the #1 runtime exception in Java applications. Eliminating null returns shifts the check to compile time via Optional.

Enforcement

NP_NULL_ON_SOME_PATH — a null pointer dereference is possible. NP_OPTIONAL_RETURN_NULL — Optional methods should not return null.

Rule: java:S2225 — "ToString" methods should not return null Rule: java:S3553 — Optional parameters should be described in Javadoc

正例

public Optional<Order> findById(Long id) {
    return orderRepository.findById(id); // ✅ returns Optional, never null
}

@Nullable
public Order findDraftByUserId(Long userId) {
    return orderRepository.findDraftByUserId(userId); // ✅ annotated as nullable
}

反例

public Order findById(Long id) {
    return orderRepository.findById(id).orElse(null); // ❌ returns null
}

public Optional<Order> findById(Long id) {
    if (id == null) {
        return null; // ❌ Optional method returning null
    }
    return orderRepository.findById(id);
}