๐ 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.