Rule Design Pattern and Open Closed Principle in 6 minutes

Doradla Hari Krishna
Javarevisited
Published in
6 min readDec 24, 2023

--

Hey there! If you’re not a Medium member, you can still read the full article by following this friend link. I hope you enjoy it :)

Background Story

I was going through a code repo at my work and saw there are bunch of `if` conditions being executed on an object and inside each `if` block fat business logic is implemented. At a glance, i was overwhelmed to see such a big function with multiple conditions and huge logic in just one file. I did some studying and came across this beautiful pattern called Rule Design Pattern. We will see in just a minute how this can make code more modular, readable, testable and maintainable.

I can’t use exact usecase that i saw at my work to demonstrate here. So i will take one realistic example and explain how we can use Rule Design Pattern on it. I hope you must be aware of coupons that Swiggy or Amazon or any other shopping platform provides us to use during cart checkout. Let’s take similar one.

Problem

Let’s assume we have a shopping platform where users can buy things. During checkout we want to provide discount coupons on customer birthday, 100th order, till end of first week from account creation, on festival days and on first order.

Naive Approach

--

--

Doradla Hari Krishna
Javarevisited

Software Engineer who likes writing about tech concepts