Member-only story

Refactoring If-Else Chains with Map in Java

Sohit Mishra
2 min readFeb 10, 2025

--

If Else

Introduction

When working with legacy Java code, it’s common to encounter long if-else chains that determine the execution flow based on input conditions. While functional, such code is often hard to maintain, read, and error-prone. A more elegant approach involves using a Map to replace these conditional statements, making the code more readable and scalable.

Problem Statement

Imagine you are working on a Java application that processes different types of user notifications. The existing implementation relies on a lengthy if-else chain:

public void sendNotification(String notificationType) {
if ("EMAIL".equals(notificationType)) {
sendEmailNotification();
} else if ("SMS".equals(notificationType)) {
sendSmsNotification();
} else if ("PUSH".equals(notificationType)) {
sendPushNotification();
} else {
sendDefaultNotification();
}
}

While this approach works, it becomes increasingly difficult to maintain as more notification types are added. Let’s explore how we can refactor this using a Map.

Solution: Using a Map

We can replace the if-else logic with a Map<String, Runnable> where each notification type maps to a corresponding method…

--

--

Sohit Mishra
Sohit Mishra

Written by Sohit Mishra

Hi, I'm Sohit Mishra, a full-stack developer obsessed with creating seamless digital experiences through front-end and back-end technologies.

No responses yet