Divergent Change

Sign of Smell

"Divergent Change" is sometimes confused with another related code smell called "Shotgun Surgery," but it is actually the opposite smell.

"Divergent Change" is a class or a module that might be changed for many different reasons all the time. On the other hand, “Shotgun Surgery” is, to make one single change, we have to change many different places at the same time.

In short, “Shotgun Surgery” triggers many changes, but “Divergent Change” is triggered by many changes.

Reason of Smell

  • Violates the Single Responsibility Principle (SRP): The SRP states that a class should have only one reason to change, meaning it should have a single responsibility.

  • Code Duplication: Divergent Change often leads to code duplication. If different parts of the codebase are making similar changes to the same module, it's a sign that functionality should be separated into distinct modules or classes to avoid redundancy.

  • Lack of Encapsulation: Encapsulation is a fundamental concept in object-oriented programming. When a class or module is undergoing divergent changes, it suggests that it may not be properly encapsulating its responsibilities, leading to a breakdown in the abstraction and separation of concerns.

  • Code Fragility: Since changes in one area of the code can affect unrelated parts, it becomes difficult to predict the impact of a modification. This makes the codebase fragile, making it more likely to break when changes are made.

  • Maintainability: When a module is responsible for multiple concerns or functionalities, any change in one of these concerns can inadvertently affect the others. This increases the complexity of maintaining the codebase because developers need to be cautious not to introduce bugs or unintended side effects.

  • Testing Challenges: Writing tests for a module that exhibits Divergent Change can be more complicated. It may require extensive test coverage to ensure that all the different aspects of the module are functioning correctly after changes.

Refactoring Recipes

Extract Class

When a code smell indicates that the current design may violate the Single Responsibility Principle (SRP), it means that the class has more than one responsibility. The recommended countermeasure is to split the extra responsibility into another independent class. This helps keep the target class simple and clean.

Extract Superclass / Extract Subclass

If different classes exhibit the same behavior, we can consider combining them through inheritance, using other refactoring techniques such as Extract Superclass or Extract Subclass.

Reference

https://refactoring.guru/smells/divergent-change

http://teddy-chen-tw.blogspot.com/2014/04/3long-parameter-list-divergent-change.html

Last updated