Turning a Java NPE Nightmare into Defensive Coding Best Practices
This article walks through a real Java NPE incident, reproduces the faulty code, analyzes each null‑pointer cause, and presents defensive programming, Optional, and utility‑method solutions, while also recommending the SonarLint plugin for early detection of such bugs.
Preface
Hello everyone, I’m Feng. This post shares a real‑world case to help you deeply understand NullPointerException (NPE) in Java.
Incident Reproduction
1. Pseudocode
The following pseudocode is not the exact production code but illustrates the scenario where NPE can occur.
// Backend channel configuration
String channelNo = channelDao.getOne().getChannelNo();
// Data fetched from a third‑party source
List<ThirdData> thirdDataList = httpClientUtils.getThirdDatas(DateUtils.today());
// Matching filter
thirdDataList.stream().filter(o -> channelNo.equals(o.getChannelNo())).collect(Collectors.toList());
// Batch insert
thirdDataDao.saveAll(thirdDataList);2. Analysis and Solutions
Experienced developers will quickly spot three potential NPE sources in the four lines above.
3. First Line Analysis
If channelDao.getOne() returns null, calling getChannelNo() throws an NPE.
4. Solutions for the First Line
1) Defensive programming with early return:
// If the channel is mandatory, return early when null
Channel channel = channelDao.getOne();
if (channel == null) {
return;
}2) Ternary operator returning an empty string:
// Return a fallback empty string
String channelNo = channelDao.getOne() == null ? "" : channelDao.getOne().getChannelNo();3) Using Optional:
String channelNo = Optional.ofNullable(channelDao.getOne()).orElse("");5. Third Line Analysis (1)
If thirdDataList is null, invoking stream() causes an NPE.
6. Solutions for the Third Line (1)
1) Defensive programming (recommended):
// Recommended: check collection emptiness
if (CollectionUtils.isEmpty(thirdDataList)) {
return;
}2) Wrapping with an if condition (not recommended):
if (CollectionUtils.isNotEmpty(thirdDataList)) {
// proceed with logic
}7. Third Line Analysis (2)
If channelNo is null, the call channelNo.equals(o.getChannelNo()) throws an NPE.
Solutions:
1) Add an explicit null check:
channelNo != null && channelNo.equals(o.getChannelNo())2) Use Objects.equals from java.util.Objects:
Objects.equals(channelNo, o.getChannelNo())3) Use other utility libraries or custom implementations.
Conclusion
I recommend the IntelliJ IDEA plugin SonarLint for real‑time detection of code issues such as NPEs.
This plugin can dynamically highlight code vulnerabilities.
SonarLint also integrates with the server‑side solution SonarQube.
Thanks for reading—please like and share if you found this helpful!
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
