Skip to main content

Command Palette

Search for a command to run...

Code Smell 08 - Long Chains Of Collaborations

Published
2 min read
Code Smell 08 - Long Chains Of Collaborations

Making long chains generate coupling and ripple effect. Any chain change breaks the code.

TL;DR: Just sent messages to your acquaintances.

Problems

  • Coupling

  • Break encapsulation

Solutions

  • Create intermediate methods.
  • Think about Law of Demeter.
  • Create higher level messages.

Sample Code

Wrong

class Dog {
   constructor(feet) {
     this.feet = feet;    
  }
  getFeet() {    
    return this.feet;
  }  
}

class Foot {
  move(){    
    //..
  }
}

feet = [new Foot(), new Foot(), new Foot(), new Foot()];
dog = new Dog(feet);

for (var foot of dog.getFeet()) {
  foot.move(); 
}

Right

class Dog {
   constructor(feet) {
     this.feet = feet;    
  }
  walk(){
    for (var foot of this.feet) {
      foot.move(); 
    }
  }
}

class Foot {
  move(){    
    //..
  }
}

feet = [new Foot(), new Foot(), new Foot(), new Foot()];
dog = new Dog(feet);
dog.walk();

Detection

Automatic detection is possible using parsing trees.

Also Known as

  • Message Chains

  • Law of Demeter

Relations

More Info

Tags

  • Declarative

  • Encapsulation

Conclusion

Avoid successive message calls. Try to hide the intermediate collaborations and create new protocols.

Credits

Photo by Chewy on Unsplash


This article is part of the CodeSmell Series.

Last update: 2021/06/10

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.