Which Design Pattern Cleans Up This If-Else Mess?
The article shows a Java if-else chain that applies different discounts and actions based on user type, then asks which design pattern can refactor it into more elegant code.
In real-world coding, we often encounter business scenarios where different input conditions trigger different logic, leading to lengthy if-else chains.
The article presents a typical example: a discount calculation that varies by user type.
if (userType.equals("common")) {
discount = 0.9;
totalAmount = discount * totalQuantity;
} else if (userType.equals("junior")) {
discount = 0.8;
totalAmount = discount * totalQuantity;
} else if (userType.equals("senior")) {
discount = 0.6;
totalAmount = discount * totalQuantity;
addCoupon();
} else if (userType.equals("super")) {
discount = 0.5;
totalAmount = discount * totalQuantity;
sendGift();
}Each branch sets a discount multiplier, computes the total amount, and for senior and super users also invokes additional behaviors (addCoupon, sendGift). The author then poses the question: what design pattern should be used to refactor this code and make it more elegant?
The provided excerpt does not include the answer or a detailed discussion of specific patterns; it ends with recommended reading links to other articles.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
