Return to site

๐Ÿ’Š Java fix: Avoiding NPE

September 7, 2025

๐Ÿ’Š 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.