The post Visualization Mnemonics for Software Principles by Erik Dietrich provides a very effective trick to understand (and never forget anymore) what the Law of Demeter is. An Italian translation is available here.
An example of code violating the Law of Demeter is provided by Krzysztof Grzybek
class Plane {
constructor(crew) {
this.crew = crew;
}
getPilotsName() {
this.crew.pilot.getName();
}
}
class Crew {
constructor(pilot) {
this.pilot = pilot;
}
}
class Pilot {
getName() {
// ...
}
}
It's bad, because it creates tight coupling between objects - they are dependent on internal structure of other objects.
Fixed code:
class Plane {
getPilotsName() {
this.crew.getPilotsName();
}
}
class Crew {
constructor(pilot) {
this.pilot = pilot;
}
getPilotsName() {
return this.pilot.getName();
}
}