💊 Java fix: Avoiding NPE
New carousel live! Swipe ▶️ to learn simple patterns that kill NullPointerException at the source.
Highlights:
- ✅ Return Collections.emptyList() (not null)
- 🧭 Guard early: Objects.requireNonNull(follower, "Follower must not be null"); sayHi(follower);
- 🟢 Fluent: Optional.ofNullable(follower).ifPresent(this::sayHi);
- 😐 Legacy (ok but noisy): if (follower != null) { sayHi(follower); }
What’s your go-to NPE defense? Drop it in the comments 👇
Oleh said:
Would also recommend trying JSpecify for better null-safety. It’s becoming the standard annotation set, integrates well with static analysis, and helps enforce null contracts consistently across the codebase. Also well supported by IDEA.
https://spring.io/blog/2025/03/10/null-safety-in-spring-apps-with-jspecify-and-null-away
===
Optional is meant to be used as return types, not ad-hoc wrappers. In this case, a simple null check is perfectly fine - it’s clearer and more straightforward.