16 Essential Coding Habits Every Java Developer Should Master
This article presents sixteen practical coding habits—from self‑testing changes and validating parameters to using thread pools and ensuring cache consistency—designed to help Java developers avoid common bugs, improve code quality, and build more reliable applications.
Preface
Every good habit is a wealth; this article lists 16 classic coding habits that can help avoid most non‑business bugs. Adopt them to improve code quality.
1. Self‑test after modifying code
After changing code, always run your own tests instead of assuming a single‑line change cannot introduce bugs.
2. Validate method parameters
Check that arguments are not null and meet expected length or format to prevent “low‑level” bugs such as database errors.
If a database column is varchar(16) and a 32‑character string is inserted without validation, an exception occurs.
3. Consider compatibility when modifying old interfaces
When changing a public interface, ensure backward compatibility, e.g., keep the old method and forward‑compatible parameters.
<code>// old interface
void oldService(A,B);
// compatible call
newService(A,B,null);
// new interface (cannot delete old one yet)
void newService(A,B,C);
</code>4. Add clear comments for complex logic
For intricate business logic, write explicit comments to aid future maintenance.
5. Close IO resources
Always close streams, preferably with try‑with‑resources in JDK 7+.
<code>FileInputStream fdIn = null;
try {
fdIn = new FileInputStream(new File("/jay.txt"));
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} finally {
try {
if (fdIn != null) {
fdIn.close();
}
} catch (IOException e) {
log.error(e);
}
}
</code> <code>try (FileInputStream inputStream = new FileInputStream(new File("jay.txt"))) {
// use resources
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
</code>6. Guard against runtime errors
Check collection size before accessing elements to avoid IndexOutOfBoundsException.
<code>if (CollectionsUtil.isNotEmpty(list) && list.size() > 1) {
String name = list.get(1).getName();
}
</code>7. Avoid remote or DB calls inside loops; batch when possible
Batch queries reduce network and IO overhead.
<code>// good
remoteBatchQuery(param);
// bad
for (int i = 0; i < n; i++) {
remoteSingleQuery(param);
}
</code>8. Think about concurrency when combining read‑modify‑write
Ensure atomicity to prevent race conditions; use database atomic delete as an example.
<code>if (deleteAvailableTicketById(ticketId) == 1) {
// add cash
} else {
return "No available coupon";
}
</code>9. Null‑check objects before accessing properties
<code>if (object != null) {
String name = object.getName();
}
</code>10. Use appropriate thread pools instead of creating new threads
Thread pools manage resources, improve response speed, and allow isolation per business domain.
11. Run SQL statements manually and examine execution plans
<code>explain select * from user where userid = 10086 or age = 18;
</code>12. Handle third‑party API calls with exception handling, timeouts, and retries
Consider signatures, encryption, and retry policies for critical services.
13. Ensure API idempotency
Use unique indexes, tokens, optimistic/pessimistic locks, or distributed locks to prevent duplicate processing.
14. Use thread‑safe collections in high‑concurrency scenarios
Prefer ConcurrentHashMap over HashMap when multiple threads access the map.
15. Consider master‑slave replication lag
For critical reads, read from the master or design accordingly.
16. Keep cache and database consistency; guard against cache penetration, avalanche, and breakdown
Understand the three cache pitfalls and design strategies to mitigate them.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.