Fundamentals 2 min read

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.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Which Design Pattern Cleans Up This If-Else Mess?

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

design patternsJavacode qualityrefactoringif-else
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.