Open-Closed Principle Scenario 1

Lets say there is a Cart class which calculates total amount based on the mode.
This below code has three modes 1. Ordinary (one unit costs 2m) 2. Special (one unit costs 1.5m) 3. Offer (one unit costs 1.25m)
Based on the modes, the calculated value changes.

Here are the basic unit test cases which checks all the three modes.

Currently all the test cases passes.

The only problem, I see in this code is, If I wanted to add a new rule, say 4. Diwali Offer (one unit costs 1m). I need to modify CalculateTotal method. This is the scenario to explain OCP (Open for extension but Closed for modificaion).

Well, I have refactored the code.

I have separated the calculation part from this Cart class like this.

In the CalculateTotal method, I’m checking the MODE and based on that I’m calculating the amount. So for every rule, the logic is same but the values change. So I have extracted the logic into a separate interface called IRule

I have implemented this interface in all rules.

So far everything is great.

Now the extension part. I need to extend the current code without modification.

Create a new rule like DiwaliOffer.cs

Extend it by including it in the rules list

I haven’t modified any business rules, i have extended it.

P.S, I’m still looking on how to automatically add the rule in the rules list. Any insights much appreciated.

Share your thoughts