
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
This article is part of the CodeSmell Series.
Last update: 2021/06/10
About the author
I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.
Comments
Join the discussionNo comments yet. Be the first to comment.
Code Smells
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.





