Fundamentals 12 min read

16 Essential Coding Habits Every Developer Should Master

This article compiles sixteen practical coding habits—from self‑testing changes and validating method parameters to handling concurrency, resource cleanup, and cache consistency—providing concrete examples, code snippets, and clear guidelines that help developers avoid common bugs and improve overall software quality.

ITPUB
ITPUB
ITPUB
16 Essential Coding Habits Every Developer Should Master

1. Test Your Changes After Modifying Code

After any code change, always run a quick self‑test to catch regressions, even if you only altered a variable or a single configuration line.

2. Validate Method Parameters

Check every incoming argument for nullability, length, and format before processing; unvalidated parameters are a frequent source of low‑level bugs.

If a database column is defined as varchar(16) and a 32‑character string is passed without validation, the insert will throw an exception.

3. Preserve Compatibility When Modifying Existing Interfaces

When changing a public API, ensure backward compatibility to avoid breaking existing clients. For example, add a new parameter to a Dubbo interface while keeping the old signature functional.

void oldService(A, B) {
    // compatible call to new service
    newService(A, B, null);
}

void newService(A, B, C);

4. Add Clear Comments for Complex Business Logic

While good naming reduces the need for comments, intricate business logic should be accompanied by concise, explanatory comments to aid future maintenance.

5. Close IO Resources After Use

Failing to close streams or database connections can exhaust system resources. Use finally blocks or Java 7+ try‑with‑resources to ensure proper cleanup.

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); }
}
try (FileInputStream inputStream = new FileInputStream(new File("jay.txt"))) {
    // use resources
} catch (FileNotFoundException e) {
    log.error(e);
} catch (IOException e) {
    log.error(e);
}

6. Guard Against Runtime Errors (Array Bounds, Division by Zero, Null Pointers)

Check collections and numeric operations before use to prevent common exceptions.

if (CollectionsUtil.isNotEmpty(list) && list.size() > 1) {
    String name = list.get(1).getName();
}

7. Avoid Remote or Database Calls Inside Loops; Prefer Batch Operations

Network and IO calls are expensive; batch them when possible, but avoid overly large batches.

remoteBatchQuery(param);
for (int i = 0; i < n; i++) {
    remoteSingleQuery(param);
}

8. Consider Concurrency Consistency When Writing Code

Operations that read‑modify‑write must be atomic. Use database atomic deletes or proper locking to avoid race conditions.

if (deleteAvailableTicketById(ticketId) == 1) {
    // increase cash
} else {
    return "No available coupon";
}

9. Null‑Check Objects Before Accessing Their Properties

Always verify an object is not null before calling its getters to prevent NullPointerExceptions.

if (object != null) {
    String name = object.getName();
}

10. Use Thread Pools Instead of Creating New Threads Directly

Thread pools reduce creation overhead, improve response time, and allow isolation of critical business workloads into separate pools with appropriate configurations.

11. Execute Raw SQL in a Database Console First and Review the Explain Plan

Running SQL manually helps catch syntax errors and reveals whether indexes are used.

explain select * from user where userid = 10086 or age = 18;

12. Handle Exceptions, Timeouts, and Retries When Calling Third‑Party Services

Define clear error‑handling strategies, set connection timeouts, and decide on retry counts based on business impact. For sensitive operations like payments, also consider signing, verification, and encryption.

13. Ensure API Idempotency

Design APIs so that repeated identical requests produce the same effect, using techniques such as unique indexes, tokens, optimistic/pessimistic locking, or distributed locks (e.g., Redis, Zookeeper).

14. Use Thread‑Safe Collections in High‑Concurrency Scenarios

Replace non‑thread‑safe structures like HashMap with ConcurrentHashMap when concurrent access is expected.

15. Account for Master‑Slave Replication Lag

When reading after a write, consider whether to force a read from the master or tolerate slight lag, depending on business criticality.

16. Maintain Cache Consistency and Guard Against Cache Pitfalls

Cache should speed up reads while staying consistent with the database. Be aware of cache penetration, cache avalanche, and cache breakdown, and apply appropriate mitigation strategies.

Concurrency flow diagram
Concurrency flow diagram
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

software developmentcode qualitycoding habits
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.