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.
How to Find the Stinky parts of your Code
Maxi Contieri ・ May 21 '21
Last update: 2021/06/10
Top comments (0)