DEV Community

loading...
Cover image for Code Smell 08 - Long Chains Of Collaborations

Code Smell 08 - Long Chains Of Collaborations

Maxi Contieri
Learn something new every day. - I am a senior software engineer working in industry, teaching and writing on software design, SOLID principles, DDD and TDD.
Originally published at maximilianocontieri.com Updated on ・1 min read

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

Discussion (0)