Backend Development 18 min read

Defensive Programming, Exception Handling, and DRY Principle in Java

The article explains how defensive programming in Java—using guard clauses, validators, and side‑effect‑free assertions—prevents errors, outlines proper exception handling by distinguishing checked from unchecked exceptions, and reinforces the DRY principle, urging developers to abstract repeated logic after three occurrences.

Youku Technology
Youku Technology
Youku Technology
Defensive Programming, Exception Handling, and DRY Principle in Java

You cannot write perfect software. Because it has never appeared and will never appear. This article discusses three important software development principles in Java: defensive programming, proper exception handling, and the DRY (Don't Repeat Yourself) principle.

Defensive Programming

Defensive programming is a technique to improve software quality. The main idea is that programs/methods should not break due to erroneous input data, even from other methods written by yourself. A good program should either output nothing or output an error message when given illegal input.

Using Guard Clauses

When checking for illegal input, we often use if-else statements, but nested conditionals can become ugly. The Java Development Manual recommends using guard clauses to handle such cases. Guard clauses split complex nested expressions into multiple expressions, handling all special cases upfront.

public void doSomething(DomainA a) {
    if (a == null) {
        return ; //log some errorA
    }
    if (a.getB() == null) {
        return ; //log some errorB
    }
    if (!(a.getB().getC instanceof DomainC)) {
        return ;//log some errorC
    }
    assignAction;
    otherAction;
    doSomethingA();
    doSomethingB();
    doSomthingC();
}

Using Validators

Validators are a practice in development that combines validation with OOP. By implementing validation interfaces on parameter objects and configuring validation annotations for fields, validation logic can be encapsulated within objects.

public List<DemoResult> demo(DemoParam dParam) {
    Assert.isTrue(dParam.validate(),()-> new SysException("参数验证失败-" + DemoParam.class.getSimpleName() +"验证失败:" + dParam));
    DemoResult demoResult = doBiz();
    doSomething();
    return demoResult;
}

Using Assertions

When an unexpected production issue occurs, we should use assertions to ensure impossible conditions never happen. The key principle is that assertions must not have side effects, and essential code should never be placed within assertions.

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();
        }
    }
}

Proper Exception Handling

Exceptions should only be used in exceptional circumstances, never for normal flow control. The article discusses checked vs. unchecked exceptions: use checked exceptions for recoverable situations and unchecked exceptions for programming errors.

DRY Principle

DRY (Don't Repeat Yourself) states that every piece of knowledge must have a single, unambiguous, authoritative representation within a system. The principle is about avoiding duplication of knowledge, not just code. The article recommends the Rule of Three: write a specific solution the first time, copy it the second time, and abstract it the third time.

JavaException Handlingsoftware engineeringcode qualityguard clausesDRY principledefensive programming
Youku Technology
Written by

Youku Technology

Discover top-tier entertainment technology here.

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.