Eliminate Excessive if‑else with Strategy, Factory, and Singleton Patterns
This article demonstrates how to replace tangled if‑else chains in business logic with three techniques—early condition checks, the Strategy pattern, and a combination of Strategy, Factory, and Singleton—using clear examples and code illustrations to make the code more maintainable and elegant.
Scenario
In everyday development, many of us write numerous if‑else statements. When the logical branches become many, the code becomes deeply nested, functional but hard to read, especially for developers who prefer clean code.
This article introduces three key techniques:
Prioritize condition checks and abort early when conditions are not met.
Apply the Strategy pattern.
Enhance the Strategy pattern with Factory and Singleton patterns.
Below is a historical example of business code that assigns VIP video membership days and lottery chances based on the price package purchased during a payment callback.
The original code is riddled with if‑else statements (click the image to enlarge).
1. Prioritize condition checks, abort early
The idea is simple: filter out invalid conditions first instead of nesting multiple if‑else blocks. The following diagram illustrates this approach.
2. Refactor with the Strategy pattern
Replace the original if‑else logic that grants different VIP days based on the price package with a Strategy pattern. The simplified action is "assign VIP video membership days according to the price package".
Although the code looks cleaner, the if‑else statements are not completely eliminated. The recharge() method can be extracted and instantiated with different strategy objects based on priceCode.
3. Combine Strategy, Factory, and Singleton
Enhance the design by introducing a Factory class and a Singleton to manage strategy instances, adding further structure and reusability.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
