link: Design Principles
Encapsulate What Varies
Overview
Encapsulate What Varies is a fundamental software design principle aimed at managing change by isolating it. This approach advises developers to separate the parts of their application that are likely to change from those that remain constant. This segregation enhances flexibility, reduces the impact of modifications, and simplifies maintenance.
Abstract
Implementing this principle correctly ensures that changes to the business requirements or technology affect minimal parts of the system, maintaining overall stability and promoting code reuse.
Content
Key Concepts
Encapsulation can be applied at various levels within a software system, primarily focusing on method and class levels:
Important
- Method Level: Encapsulate the changing aspects within a method to prevent changes to its implementation from affecting its callers. This makes the public interface of methods stable despite internal changes.
- Class Level: Use interfaces or abstract classes to create a flexible and stable foundation, allowing implementations to vary without impacting dependent classes.
Method Level
Method level encapsulation focuses on keeping the variability within a method, so that changes to how something is done don’t affect those who rely on the method. This means the method’s interface (signature) stays constant even if the implementation changes.
In this example, the
ProcessPayment
method encapsulates the variations in payment processing methods. This isolation prevents the need to modify calling code if new payment methods are added or existing methods are changed.
Class Level
Class level encapsulation involves isolating changes to a class so that alterations within the class do not impact its clients. This is often achieved using abstraction (interfaces or abstract classes) to interact with the class.
In this scenario, the
Application
class is designed to use anILogger
to log messages. The specific type of logger (FileLogger
orConsoleLogger
) can vary, but as long as they implement theILogger
interface, theApplication
class does not need to change. This encapsulation allows the logger to be swapped without affecting theApplication
’s operation.
Benefits of Encapsulation
Encapsulating variability not only reduces the complexity and increases the modularity of code but also allows for:
- Enhanced Flexibility: Adjustments or improvements can be made with minimal system-wide repercussions.
- Easier Maintenance and Testing: Isolated changes make the system easier to debug and test.
- Increased Code Reuse: Stable interfaces promote reusability across different parts of the application or in future projects.