Skip to content

Latest commit

 

History

History
55 lines (44 loc) · 1.46 KB

File metadata and controls

55 lines (44 loc) · 1.46 KB

Law of Demeter

Mnemonic for the Law of Demeter

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.

Code Example

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();
    }
}