Always validate null parameters and dependencies early with proper ordering to prevent NullPointerExceptions and provide clear error messages. Use defensive programming practices including parameter validation, method overloading instead of null parameter handling, and careful ordering of null checks.
Always validate null parameters and dependencies early with proper ordering to prevent NullPointerExceptions and provide clear error messages. Use defensive programming practices including parameter validation, method overloading instead of null parameter handling, and careful ordering of null checks.
Key practices:
Objects.requireNonNull()
with descriptive messagesExample of proper null validation ordering:
public record CommittedPartitionState(Set<Integer> isr, LeaderRecoveryState leaderRecoveryState) {
public CommittedPartitionState {
Objects.requireNonNull(isr); // Check null first
this.isr = Set.copyOf(isr); // Then perform operations
Objects.requireNonNull(leaderRecoveryState);
}
}
Example of method overloading instead of null checks:
// Instead of: props(Properties extraProperties) with null check
private Properties props() { /* base implementation */ }
private Properties props(Properties extraProperties) {
Properties config = props();
config.putAll(extraProperties); // No null check needed
return config;
}
This approach prevents NPEs, provides clearer stack traces when failures occur, and makes the code’s null-handling contract explicit to callers.
Enter the URL of a public GitHub repository