Backend Development 9 min read

Mastering If‑Else: 9 Proven Techniques to Simplify Java Logic

This article presents nine practical techniques—including the Strategy pattern, lambda maps, Optional chaining, ternary operators, enums, early returns, condition merging, and rule engines—to replace cumbersome if‑else chains in Java, offering cleaner, more maintainable and performant code for Spring Boot developers.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering If‑Else: 9 Proven Techniques to Simplify Java Logic

1. Introduction

When faced with many if‑else statements, developers need more efficient and maintainable solutions. While simple conditions can be handled with if‑else, complex scenarios lead to tangled code and performance issues.

This article presents nine optimization techniques to improve the use of if‑else in Java.

2. Practical Cases

2.1 Strategy Pattern

Example of a naive if‑else mapping numbers to weekdays, followed by a refactor using the Strategy pattern with an interface and concrete strategy classes.

<code>public String getDayOfWeek(int dayNumber) {
    if (dayNumber == 1) {
        return "Monday";
    } else if (dayNumber == 2) {
        return "Tuesday";
    } else if (dayNumber == 3) {
        return "Wednesday";
    } else if (dayNumber == 4) {
        return "Thursday";
    } else if (dayNumber == 5) {
        return "Friday";
    } else if (dayNumber == 6) {
        return "Saturday";
    } else if (dayNumber == 7) {
        return "Sunday";
    } else {
        return "Invalid day number";
    }
}</code>
<code>// Interface
public interface DayOfWeekStrategy {
    String getDayOfWeek();
}

// Concrete strategy example
public class MondayStrategy implements DayOfWeekStrategy {
    @Override
    public String getDayOfWeek() {
        return "Monday";
    }
}

// Factory
public class DayOfWeekStrategyFactory {
    public static DayOfWeekStrategy getStrategy(int dayNumber) {
        return switch (dayNumber) {
            case 1 -> new MondayStrategy();
            case 2 -> new TuesdayStrategy();
            // ... other cases
            default -> new InvalidDayStrategy();
        };
    }
}

// Invalid strategy
public class InvalidDayStrategy implements DayOfWeekStrategy {
    @Override
    public String getDayOfWeek() {
        return "Invalid day number";
    }
}</code>

Drawbacks: many strategy classes increase class count and may not suit deep nesting.

2.2 Strategy Variant with Map of Runnables

<code>Map<String, Runnable> actions = new HashMap<>();
actions.put("condition1", () -> { /* implementation 1 */ });
actions.put("condition2", () -> { /* implementation 2 */ });
// ...
Runnable action = actions.get("condition1");
if (action != null) {
    action.run();
}</code>

This separates business logic but can still lead to a bulky class if conditions are numerous.

2.3 Nested if‑else Simplification with Optional

<code>Order order = new Order();
Optional.ofNullable(order)
    .map(Order::getOrderItem)
    .map(OrderItem::getOrderItemDetail)
    .map(OrderItemDetail::getProduct)
    .filter(Objects::nonNull)
    .ifPresent(System.out::println);
</code>

2.4 Ternary Operator

<code>String desc;
if (condition1) {
    desc = "XX1";
} else if (condition2) {
    desc = "XX2";
} else {
    desc = "XX3";
}
</code>

Or in a single expression:

<code>String desc = condition1 ? "XX1" : (condition2 ? "XX2" : "XX3");</code>

2.5 Enum‑Based Logic

<code>public class OrderService {
    public double calculateDiscount(String userType, double amount) {
        if ("VIP".equals(userType)) {
            return amount * 0.8;
        } else if ("ENTERPRISE".equals(userType)) {
            return amount * 0.7;
        } else if ("REGULAR".equals(userType)) {
            return amount * 0.95;
        } else {
            return amount; // no discount
        }
    }
}
</code>

Refactored with an enum that encapsulates discount logic, reducing the conditional chain.

2.6 Early Return

<code>if (condition1) {
    return;
}
if (condition2) {
    return;
}
// ...
</code>

Placing the most frequent conditions first and returning early improves performance.

2.7 Eliminate Redundant Branches

<code>if (!condition) {
    return;
}
</code>

Or directly return the boolean expression:

<code>return !condition;</code>

2.8 Merge Conditions

<code>double calculateShipping() {
    if (orderAmount > 1000 || customerLoyaltyLevel > 5 || promotionIsActive) {
        return 0.5;
    }
}
</code>

2.9 Rule Engine

For frequently changing business rules, a rule engine such as Drools, Easy Rules, LiteFlow, or Spring Expression Language (SpEL) can decouple logic from code, improve manageability, and allow business users to participate in decision making.

These nine techniques help developers replace bulky if‑else chains with cleaner, more maintainable, and often more performant alternatives.

backenddesign patternsJavacode optimizationSpring Bootif-else
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

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.