Open Closed principle and Rule engine design pattern
Respect the privacy.
The SOLID principle is a subset of the many tenets promoted by American software engineer and instructor Robert C Martin, known as “Uncle Rob.” In this article, I would be talking about one of the S{O}LID principles, i.e., Open-Closed Principle(OCP).
I would use C# for demonstrating code, but OCP is language-agnostic.
The official definition of OCP is:
software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification
Benefits of OCP
OCP recommends practices that make it easy to upgrade software applications. Imagine a use case where WhatsApp wants to extend the chat service to send messages to Facebook messenger.
The developers would like to re-use relevant components of the chat service. There are two ways of doing it.
- Modify existing chat service to support the new requirement. It will expose the chat service code to bugs. The complexity of chat service will increase, and automated test cases might fail.
- Extend the chat service code by using relevant components. The code written to support new features will be in the form of new classes but will benefit from the core functionality of the chat service. The benefit of this approach is that new features can be deployed and tested independently.
Rule Engine design pattern is one of the many ways to obey OCP. Many other design patterns allow us to follow OCP, but I am limiting this session to the Rule Engine design pattern, which is one of the easiest ways to demonstrate the power of OCP.
Rule Engine
One of the popular design patterns to help developers follow OCP is the Rule Engine design pattern. It is an efficient design pattern to develop software applications with multiple and complex business rules processing the same entity.
Business rules could be correlated and complex. There could be a lot of complicated branching and conditional logic involved. Following OCP will enable the developers to add, remove or disable business results independently.

There are two components of a Rule Engine:
- Rule Engine — An Engine that executes all rules on an entity to produce a result.
- Business Rule — A Rule defines a processing logic or a condition.
A Tax Calculator
Let’s try and implement Rule Engine design pattern for a Tax Calculator application. Tax Calculation is a complex process and depends on many factors like Age, Gross Income, Residency status, etc. A lot of business rules evaluate these factors to determine Tax amount. Government policies drive these business rules and can change them frequently. I will use the Rule Engine design pattern to keep these business rules independent in this use case.

Steps to implement Rule Engine Design pattern
Complete code can be found at https://github.com/tarunbhatt9784/TaxCalculator.git
Step 1 — Write all the rules in one place
Write all rules in one method using if-then-else conditional statements.






