Fundamentals 19 min read

Write Robust Java Code: Defensive Programming, Smart Exceptions & DRY

This article explains how to write robust Java code by applying defensive programming, using guard clauses, proper exception handling, validator patterns, assertions, and the DRY principle, offering concrete code examples and practical advice for building reliable software.

Alibaba Cloud Developer
Alibaba Cloud Developer
Alibaba Cloud Developer
Write Robust Java Code: Defensive Programming, Smart Exceptions & DRY

Defensive Programming

Defensive programming aims to keep a method from being broken by invalid input, even when that input originates from other parts of the same system. A robust program should either produce no output or emit a clear error message when faced with illegal data.

Guard Clauses

Instead of deep nested if…else blocks, use guard clauses to handle error cases early and return, keeping the normal execution path clear.

public void doSomething(DomainA a) {
    if (a == null) {
        return; // log error A
    }
    if (a.getB() == null) {
        return; // log error B
    }
    if (!(a.getB().getC() instanceof DomainC)) {
        return; // log error C
    }
    assignAction;
    otherAction;
    doSomethingA();
    doSomethingB();
    doSomthingC();
}

Validator Pattern

Encapsulate parameter validation in a validator object and invoke it at the start of a method.

public List<DemoResult> demo(DemoParam dParam) {
    Assert.isTrue(dParam.validate(), () -> new SysException("Parameter validation failed-" + DemoParam.class.getSimpleName() + " validation failed:" + dParam));
    DemoResult demoResult = doBiz();
    doSomething();
    return demoResult;
}

Assertions

Use assertions for conditions that should never happen in production, but avoid side effects and never place essential code inside an assertion. Prefer Spring's Assert utilities, which throw IllegalStateException when a condition fails.

public class Assert extends org.springframework.util.Assert {
    public static <T extends RuntimeException> void isTrue(boolean expression, Supplier<T> tSupplier) {
        if (!expression) {
            if (tSupplier != null) {
                throw tSupplier.get();
            }
            throw new IllegalArgumentException();
        }
    }
}

Exception Handling

Check every possible error, especially unexpected ones. Use checked exceptions for recoverable situations (e.g., file access) and unchecked exceptions for programming errors. Do not misuse exceptions to control normal flow.

public static void openPasswd() throws FileNotFoundException {
    FileInputStream fs = new FileInputStream("/etc/passwd");
}

public static boolean openUserFile(String path) throws FileNotFoundException {
    File f = new File(path);
    if (!f.exists()) {
        return false;
    }
    FileInputStream fs = new FileInputStream(path);
    return true;
}

DRY Principle

The DRY (Don’t Repeat Yourself) principle states that each piece of knowledge should have a single, authoritative representation. Apply it wisely: avoid unnecessary duplication, but also consider YAGNI and the Rule of Three to decide when abstraction is worthwhile.

EVERY PIECE OF KNOWLEDGE MUST HAVE A SINGLE, UNAMBIGUOUS, AUTHORITATIVE REPRESENTATION WITHIN A SYSTEM.

Over‑applying DRY can lead to premature abstraction; under‑applying it creates maintenance headaches. Balance is key.

Conclusion

Principles like defensive programming, proper exception usage, guard clauses, validators, assertions, and DRY are tools to help write reliable, maintainable code. Use them thoughtfully, adapt to the context, and avoid treating any principle as a silver bullet.

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.

JavaException HandlingDRY principledefensive programmingcode robustness
Alibaba Cloud Developer
Written by

Alibaba Cloud Developer

Alibaba's official tech channel, featuring all of its technology innovations.

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.