Fundamentals 12 min read

16 Essential Coding Habits Every Developer Should Follow

This article compiles sixteen practical coding habits—ranging from self‑testing and parameter validation to concurrency safety, cache consistency, and proper resource handling—to help developers avoid common bugs and write more reliable, maintainable software.

Architect
Architect
Architect
16 Essential Coding Habits Every Developer Should Follow

1. Self‑test after modifying code

Always test your changes, even if you only altered a variable or a single configuration line, to prevent unnecessary bugs.

2. Validate method parameters

Check for null values, length constraints, and other expectations before processing; many low‑level bugs stem from missing validation.

If a database field is defined as varchar(16) but a 32‑character string is passed without validation, an insertion error occurs.

3. Consider interface compatibility when modifying old APIs

Changing public interfaces without backward compatibility can cause release failures. For example, when extending a Dubbo interface, provide a compatible overload:

// old interface
void oldService(A, B) {
  // adapt to new interface
  newService(A, B, null);
}

// new interface
void newService(A, B, C);

4. Add clear comments for complex logic

When business logic is intricate, detailed comments improve maintainability.

5. Close IO resources after use

Unclosed streams waste resources; always close them, preferably using try‑with‑resources in JDK 7+.

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 (e.g., array out‑of‑bounds, division by zero)

Validate collections before accessing elements:

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

7. Batch remote or database calls instead of looping single requests

Batch queries reduce network and IO overhead; avoid per‑iteration remote calls.

remoteBatchQuery(param);

8. Think about multithreaded execution and consistency

Combine read‑modify‑write operations atomically to avoid race conditions, e.g., use an atomic delete‑then‑update pattern.

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

9. Null‑check objects before accessing properties

Always verify an object is not null before calling its methods.

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

10. Use appropriate thread pools instead of creating raw threads

Thread pools manage resources, improve response time, and should be isolated per business domain.

11. Run and explain SQL statements manually before deployment

Execute SQL in the database and review the execution plan to catch syntax errors and index usage.

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

12. Handle third‑party API exceptions, timeouts, and retries

Set connection timeouts, define retry counts, and consider security measures like signing and encryption for critical services.

13. Ensure API idempotency

Design APIs to produce the same effect regardless of repeated calls, using techniques such as unique indexes, tokens, or distributed locks.

14. Consider linear safety in high‑concurrency scenarios

Replace non‑thread‑safe collections (e.g., HashMap) with thread‑safe alternatives like ConcurrentHashMap.

15. Account for master‑slave replication lag

For critical reads, consider forcing queries to the master or redesigning to tolerate slight delays.

16. Maintain cache‑DB consistency and guard against cache penetration, avalanche, and breakdown

Use strategies such as cache pre‑warming, Bloom filters, and fallback mechanisms to protect the database.

For more technical articles, follow the public account, share the post, and contact the author for further learning.

TestingConcurrencyResource Managementsoftware developmentcode qualitycoding best practices
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

login 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.