How to Eliminate Excessive if…else: 8 Proven Refactoring Techniques
This article examines the problems caused by overusing if…else statements—such as reduced readability, maintainability, and extensibility—and presents eight practical solutions including table‑driven design, chain‑of‑responsibility, annotation‑driven, event‑driven, state machines, Optional, Assert, and polymorphism, plus additional tactics like method extraction and guard clauses.
In real‑world code, excessive if…else statements harm readability and maintainability, violating the Single Responsibility and Open/Closed principles and limiting extensibility.
Problem 1: Too Many if…else
Symptoms
Code with many branches (often more than 5) becomes hard to read and extend; each additional branch increases complexity.
if (condition1) {
// ...
} else if (condition2) {
// ...
} else if (condition3) {
// ...
} else if (condition4) {
// ...
} else {
// ...
}Such code usually breaks the Single Responsibility and Open/Closed principles.
How to Solve
The following methods can replace bulky if…else structures.
Table‑Driven Map fixed logical expressions to actions using a lookup table.
Map<?, Function<?>> actionMappings = new HashMap<>();
actionMappings.put(value1, (params) -> doAction1(params));
actionMappings.put(value2, (params) -> doAction2(params));
// ...
actionMappings.get(param).apply(params);Chain of Responsibility Delegate condition checks to a chain of handlers.
public void handle(Request r) {
handlerA.handleRequest(r);
}
abstract class Handler {
protected Handler next;
public abstract void handleRequest(Request r);
public void setNext(Handler n) { this.next = n; }
}
class HandlerA extends Handler {
public void handleRequest(Request r) {
if (canHandle(r)) doHandle(r);
else if (next != null) next.handleRequest(r);
}
}Annotation‑Driven Use annotations (or similar mechanisms) to declare execution conditions, then invoke methods via reflection or a table.
Event‑Driven Link events to handlers, achieving loose coupling; suitable for scenarios like order‑payment triggering inventory updates.
Finite State Machine Model states and transitions; useful for protocols, order processing, etc.
Optional Replace null‑checks with {@code Optional} to avoid explicit if…else.
Optional<String> opt = Optional.of("Hello");
opt.ifPresentOrElse(System.out::println, () -> System.out.println("Null"));Assert Use validation utilities (e.g., Spring {@code Assert}, Apache Commons {@code Validate}) to replace repetitive checks.
Polymorphism Replace conditionals with subclass implementations; see Refactoring Catalog for details.
Problem 2: Deeply Nested if…else
Symptoms
Deep nesting makes code hard to follow.
if (c1) {
if (c2) {
if (c3) {
// ...
}
}
}How to Solve
Use method extraction and guard clauses to flatten structure.
public void add(Object element) {
if (readOnly) return;
if (overCapacity()) grow();
addElement(element);
} double getPayAmount() {
if (isDead) return deadAmount();
if (isSeparated) return separatedAmount();
if (isRetired) return retiredAmount();
return normalPayAmount();
}Problem 3: Complex Conditional Expressions
Symptoms
Long boolean expressions are hard to understand.
if ((c1 && c2) || ((c2 || c3) && c4)) { /* ... */ }How to Solve
Extract the expression into a well‑named method or variable.
Summary
Eight main techniques—table‑driven, chain of responsibility, annotation‑driven, event‑driven, state machine, {@code Optional}, {@code Assert}, and polymorphism—plus method extraction and guard clauses, can significantly reduce and simplify excessive if…else structures, improving code readability, extensibility, and overall software quality.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
