Code Smell 08 - Long Chains Of Collaborations

mcsee

Maxi Contieri

Posted on October 27, 2020

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(); 
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
mcsee
Maxi Contieri

Posted on October 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related