Have you ever had to modify one part of your system, only to touch five other files?
Or noticed that every time a business rule changes, you need to dig through unrelated code just to find where that logic lives?
If yes, then your code is likely violating one of the foundational design principles behind flexible and maintainable systems: Encapsulate What Varies.
In this chapter, we’ll break down what this principle means, why it matters, and how you can apply it to isolate change and protect your code from ripple effects.
Identify the parts of your code that are likely to change and separate them from the parts that stay the same.
This principle comes from the Strategy Pattern and other object-oriented design ideas that encourage you to wrap volatile behavior in a separate class or module.
Instead of letting changes leak into your stable code, you encapsulate the variation behind an interface, abstract class, or delegation.
In simpler terms:
Let’s say you are building a payment system that currently supports credit card payments.
Here’s your first version:
Then one day, the business wants to support UPI.
Then PayPal.Then Apple Pay.
So you keep adding if-else statements:
This approach becomes messy fast:
pay() functionThe part that varies here is the payment strategy.
Let’s encapsulate it.
Now, if a new payment method is introduced, no existing code needs to be modified. You simply implement a new strategy.
Apply “Encapsulate What Varies” when:
While encapsulating variation is powerful, don’t apply it prematurely.
If you only have one behavior and no foreseeable need to change it, abstraction may introduce unnecessary complexity.
Follow the Rule of Three:
The third time you need to change something, consider extracting it.
Software is always changing. The key is to change it without breaking everything else.
Encapsulating variation allows you to build flexible systems where each piece can evolve independently.
So the next time you write a function with too many if statements or see logic changing in unpredictable ways, ask yourself:
“What’s the part that keeps changing?”“Can I put that in its own class or module?”
Because once you identify what varies, you can design for change—without fear of chaos.