Member-only story
Refactoring If-Else Chains with Map in Java
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…