Member-only story

Ditch If-Else! Use Map for Clean & Efficient Code (Java Example)”

Sanjay Singh
1 min readJan 31, 2025

--

πŸš€ Introduction

Tired of messy if-else chains? Let’s replace them with a Map for better readability and performance. just code!

Ditch If-Else! Use Map for Clean & Efficient Code (Java Example)

The Problem: Too Many If-Else Statements

public class DiscountService {
public static double getDiscount(String customerType) {
if ("GOLD".equals(customerType)) {
return 20.0;
} else if ("SILVER".equals(customerType)) {
return 10.0;
} else if ("BRONZE".equals(customerType)) {
return 5.0;
} else {
return 0.0;
}
}
}

Too many if-else conditions make code harder to maintain. Let’s simplify it using a Map.

import java.util.Map;

public class DiscountService {
private static final Map<String, Double> DISCOUNT_MAP = Map.of(
"GOLD", 20.0,
"SILVER", 10.0,
"BRONZE", 5.0
);

public static double getDiscount(String customerType) {
return DISCOUNT_MAP.getOrDefault(customerType, 0.0);
}
}

🎯 Why This Is Better?

  • Cleaner Code β€” No long if-else chains.
  • Better Performance β€” Constant time lookup (O(1)).
  • Easier to Maintain β€” Just update the map, no code rewrites.

πŸ”₯ That’s it! Say goodbye to if-else chains forever! πŸš€

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet