Member-only story
Ditch If-Else! Use Map for Clean & Efficient Code (Java Example)β
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!
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! π