Turn Messy if‑else Statements into Clean, Maintainable Java Code

This article demonstrates how to replace traditional if‑else structures with guard clauses, Java Optional, and various strategy pattern implementations—including polymorphic classes, static maps, Spring‑managed beans, enums, and functional lambdas—to produce clearer, more maintainable code.

Huawei Cloud Developer Alliance
Huawei Cloud Developer Alliance
Huawei Cloud Developer Alliance
Turn Messy if‑else Statements into Clean, Maintainable Java Code

Why Simple if‑else Is Not Enough

Although if‑else is a common coding habit for small programs, relying on it heavily can lead to unclear and hard‑to‑maintain code for experienced developers.

1. Guard Clause Early Return

if (condition) {
    // do something
} else {
    return xxx;
}

if (!condition) {
    return xxx;
}
// do something

2. Simplify Null Checks with Optional

2.1 Simplify Single‑Level Null Check

if (input != null) {
    // return value 1
} else {
    // return value 2
}

return Optional.ofNullable(input)
    .map(value1)
    .orElse(value2);

2.2 Simplify Multi‑Level Null Check

if (input != null && input.getUser() != null && input.getUser().getName() != null) {
    // do action 1
} else {
    // do action 2
}

Optional.ofNullable(input)
    .map(Input::getUser)
    .map(User::getName)
    .map(action1)
    .orElse(action2);

When there is no else branch, ifPresent can be used:

if (input != null && input.getUser() != null && input.getUser().getName() != null) {
    // do action
}

Optional.ofNullable(input)
    .map(Input::getUser)
    .map(User::getName)
    .ifPresent(action);

3. Strategy Pattern Refactoring

3.1 Polymorphism

public interface Strategy {
    void invoke(); // handle specific logic
}

public class DogStrategy implements Strategy {
    @Override
    public void invoke() {
        // handle dog
    }
}

public class CatStrategy implements Strategy {
    @Override
    public void invoke() {
        // handle cat
    }
}

public class PigStrategy implements Strategy {
    @Override
    public void invoke() {
        // handle pig
    }
}

public class RabbitStrategy implements Strategy {
    @Override
    public void invoke() {
        // handle rabbit
    }
}

3.1.1 Static Map Registration

Map<String, Strategy> map = ImmutableMap.<String, Strategy>builder()
    .put("dog", new DogStrategy())
    .put("cat", new CatStrategy())
    .put("pig", new PigStrategy())
    .put("rabbit", new RabbitStrategy())
    .build();

3.1.2 Spring‑Managed Dynamic Registration

public enum StrategyMapping {
    INSTANCE;
    private final Map<String, Class<? extends Strategy>> map = new ConcurrentHashMap<>();
    public void register(String type, Class<? extends Strategy> clazz) {
        map.put(type, clazz);
    }
    public Strategy getStrategy(String type) {
        Class<? extends Strategy> clazz = map.get(type);
        if (clazz == null) {
            throw new UnregisteredException();
        }
        return SpringContextHolder.getBean(clazz);
    }
}

@Component
public class DogStrategy implements Strategy {
    @PostConstruct
    public void init() {
        StrategyMapping.INSTANCE.register("dog", this.getClass());
    }
    @Override
    public void invoke() {
        // handle dog
    }
}

Strategy strategy = StrategyMapping.INSTANCE.getStrategy(petType);
strategy.invoke();

3.2 Enum as Strategy

public enum PetType {
    DOG {
        @Override public void invoke() { /* handle dog */ }
    },
    CAT {
        @Override public void invoke() { /* handle cat */ }
    },
    PIG {
        @Override public void invoke() { /* handle pig */ }
    },
    RABBIT {
        @Override public void invoke() { /* handle rabbit */ }
    };
    public abstract void invoke();
}

PetType petType = PetType.valueOf(type.toUpperCase(Locale.ROOT));
petType.invoke();

3.3 Functional Simplification with Lambdas

Map<String, Runnable> map = ImmutableMap.<String, Runnable>builder()
    .put("dog", () -> { /* handle dog */ })
    .put("cat", () -> { /* handle cat */ })
    .put("pig", () -> { /* handle pig */ })
    .put("rabbit", () -> { /* handle rabbit */ })
    .build();

Runnable task = map.get(petType);
task.run();

By applying guard clauses, Optional, and various strategy pattern techniques, developers can replace tangled if‑else chains with clearer, more modular, and easier‑to‑maintain Java code.

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.

JavaStrategy Patternoptionalif-else refactoring
Huawei Cloud Developer Alliance
Written by

Huawei Cloud Developer Alliance

The Huawei Cloud Developer Alliance creates a tech sharing platform for developers and partners, gathering Huawei Cloud product knowledge, event updates, expert talks, and more. Together we continuously innovate to build the cloud foundation of an intelligent world.

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.