Code Smell 124 - Divergent Change

Code Smell 124 - Divergent Change

You change something in a class. You change something unrelated in the same class

Maxi Contieri
·Mar 24, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Context
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • Relations
  • More Info

TL:DR; Classes should have just one responsibility and one reason to change.

Problems

  • Coupling

  • Code Duplication

  • Low Cohesion

  • Single Responsibility Principle violation

Solutions

  1. Extract class

Context

We create classes to fulfill responsibilities.

If an object does too much, it might change in different directions.

Sample Code

Wrong

class Webpage {

  renderHTML(): {
    renderDocType();
    renderTitle();
    renderRssHeader();
    renderRssTitle();
    renderRssDescription();
   // ...
  }
  //HTML render can change

  renderRssDescription() {
   // ...
  }

  renderRssTitle() {
   // ...
  }

  renderRssPubDate() {
   // ...
  }
  //RSS Format might change

}

Right

class Webpage {

  renderHTML() {
    this.renderDocType();
    this.renderTitle();
    (new RSSFeed()).render();
    this.renderRssTitle();
    this.renderRssDescription();
   // ...
  }
  //HTML render can change
}

class RSSFeed {
  render() {
    this.renderDescription();
    this.renderTitle();
    this.renderPubDate();
    //...
  }  
  //RSS Format might change
  //Might have unitary tests 
  //etc
}

Detection

[X] Semi Automatic

We can automatically detect large classes or track changes.

Tags

  • Coupling

Conclusion

Classes must follow the Single Responsibility Principle and have just one reason to change.

If they evolve in different ways, they are doing too much.

Relations

More Info


A design that doesn’t take change into account risks major redesign in the future.

Erich Gamma


This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com