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.

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.