How to Prevent NPEs in Java: Defensive Coding Tips for New Developers
This article walks through a real‑world NPE incident in a Java SpringBoot service, demonstrates how four lines of code can cause three null‑pointer exceptions, and provides practical defensive‑programming solutions such as early returns, ternary checks, Optional, and utility methods to eliminate these bugs.
Introduction
A junior Java developer was assigned a simple task: fetch third‑party data, match it to internal channels, and batch insert it. After deployment an NPE occurred, prompting a thorough analysis of the root causes and fixes.
Incident Reproduction
Pseudocode
Explanation : The following pseudocode is not the actual production code but illustrates the scenario where NPEs are hidden and hard to detect in tests.
// Backend channel
String channelNo = channelDao.getOne().getChannelNo();
// Third‑party data
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);Analysis and Solution
The four lines above can each trigger an NPE. Below is a line‑by‑line analysis and corresponding fixes.
First Line
If channelDao.getOne() returns null, calling getChannelNo() throws an NPE.
Solution
Defensive programming with early return:
Channel channel = channelDao.getOne();
if (channel == null) {
return;
}Use ternary operator to provide a fallback empty string:
String channelNo = channelDao.getOne() == null ? "" : channelDao.getOne().getChannelNo();Leverage Optional to supply a default value:
String channelNo = Optional.ofNullable(channelDao.getOne()).orElse("");Second Line
If thirdDataList is null, invoking stream() causes an NPE.
Solution
Defensive check using collection utilities (recommended):
if (CollectionUtils.isEmpty(thirdDataList)) {
return;
}Wrap with an if condition (not recommended):
if (CollectionUtils.isNotEmpty(thirdDataList)) {
// proceed with logic
}Third Line
If channelNo is null, calling channelNo.equals(...) throws an NPE.
Solution
Add an explicit null check before calling equals:
channelNo != null && channelNo.equals(o.getChannelNo())Use Objects.equals which handles nulls safely:
Objects.equals(channelNo, o.getChannelNo())Employ third‑party utilities such as StringUtils (Apache Commons) or StrUtil (Hutool) for null‑safe comparisons.
Conclusion
The author recommends installing the SonarLint plugin for IntelliJ IDEA, which can dynamically detect code risks like NPEs. For a more comprehensive analysis, the companion server SonarQube can be used.
SonarLint
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 Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
