By | May 20, 2025

How To Avoid If Else In Java

Avoiding if-else statements in Java is often a goal in clean code, functional programming, or object-oriented design to improve readability, maintainability, and scalability. Here are several ways to achieve that, depending on the situation:

🔁 1. Use Polymorphism (Object-Oriented Design)

Replace conditionals with dynamic method dispatch using inheritance or interfaces.

Before (with if-else):

javaCopyEditif (shape.equals("circle")) {
    drawCircle();
} else if (shape.equals("square")) {
    drawSquare();
}

After (with polymorphism):

javaCopyEditinterface Shape {
    void draw();
}

class Circle implements Shape {
    public void draw() { System.out.println("Drawing Circle"); }
}

class Square implements Shape {
    public void draw() { System.out.println("Drawing Square"); }
}

// Usage:
Shape shape = new Circle();  // or new Square()
shape.draw();

🗺️ 2. Use a Map of Functions (Functional Style)

Use a Map to associate keys with behaviors, avoiding conditional logic.

javaCopyEditMap<String, Runnable> actions = new HashMap<>();
actions.put("start", () -> System.out.println("Started"));
actions.put("stop", () -> System.out.println("Stopped"));

String command = "start";
actions.getOrDefault(command, () -> System.out.println("Unknown")).run();

🧮 3. Use the Ternary Operator (For Simple Conditions)

Great for concise value selection.

javaCopyEditString status = isLoggedIn ? "Welcome back!" : "Please log in.";

🧑‍🍳 4. Strategy Pattern

Use when you have multiple behaviors and want to swap them dynamically.

javaCopyEditinterface PaymentStrategy {
    void pay();
}

class CreditCardPayment implements PaymentStrategy {
    public void pay() { System.out.println("Paid with Credit Card"); }
}

class PayPalPayment implements PaymentStrategy {
    public void pay() { System.out.println("Paid with PayPal"); }
}

// Use:
PaymentStrategy strategy = new PayPalPayment(); // chosen dynamically
strategy.pay();

🧰 5. Enum with Behavior

Encapsulate logic inside enum constants instead of using if-else.

javaCopyEditenum Operation {
    ADD { public int apply(int x, int y) { return x + y; } },
    SUBTRACT { public int apply(int x, int y) { return x - y; } };

    public abstract int apply(int x, int y);
}

// Use:
int result = Operation.ADD.apply(5, 3);  // 8

⏱️ 6. Switch Expressions (Java 14+)

Use new switch expressions for clearer multi-branch logic.

javaCopyEditString message = switch (statusCode) {
    case 200 -> "OK";
    case 404 -> "Not Found";
    default -> "Unknown";
};

✅ When to Keep if-else

  • Simple conditions (e.g., if (value == null) return;) are fine.
  • Don’t over-engineer for readability—replace if-else only when it improves clarity or extensibility.