carlos caballero
Angular
JavaScript
NestJS
NodeJS
TypeScript
UI-UX
ZExtra

Demeter's Law: Don't talk to strangers!

5 min read

What is Demeter's Law?

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs - Wikipedia

This law was proposed by Ian Holland in 1987 when he and his colleagues were programming a system called Demeter using oriented object programming. During the development of the system they realized that the code that fulfilled a series of rules was less coupled.

The Demeter's law is known as don't talk to strangers because any method of an object only can call to methods of:

  1. Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  2. Each unit should only talk to its friends; don't talk to strangers.
  3. Only talk to your immediate friends.

More formally, the Law of Demeter requires that a method m of an object O may only invoke the methods of the following kinds of objects:

  • O itself.
  • m's parameters.
  • Any objects created/instantiated within m.
  • O's direct component objects.
  • A global variable, accessible by O, in the scope of m.

In summary, all of the above rules can be stated as that you should avoid invoking methods of a member object returned by another method. In the modern object oriented languages the identifier used is dot or ->. Therefore the Demeter's law is violated when the code has more than one step between classes, i.e the following code show an example in which Demeter's law is violated:

a.getB().methodB(); // Violated Demeter's law
a.methodB(); // Don't violated Demeter's law

In this case, an object a from the A class can request a method of an object instanced of B class but the object A should not reach object B directly due to that would mean the object A has greater knowledge of object B's internal structure (tight coupling).

The following image illustrated who are friends between classes relations.

law_of_demeter_illustrated

Real example - Person --> House --> Address

Now, I am going to show a real example implemented using TypeScript as programming language. In the following UML diagram you can see as a Person is related with House and House is related with Address.

Demeter-Laws

The original code is from https://github.com/tavaresasilva/LoDRaV and it's coding using JAVA.

The following code can be run in the client/context whereas the first code broke Demeter's Law due to Person requires a knowledge about the inner implementation of the class House. On the other hand, the second implementation respects Demeter's Law and the code is less coupled.

import { FakeObject } from "./interfaces/fake-object";
// Create a person
const person = FakeObject.createAPerson();

// Example 1: Violated the Demeter's Law
console.log(
  person
    .getHouse() // return an House's object
    .getAddress() // return an Address's object
    .getZipCode() // return a ZipCode Object
);

// Example 1: Not violate the Demeter's Law
console.log(person.getZipCode());

The following steps shown as you must implemented the code to respect Demeter's Law and obtain a code less coupled. So, the first step is created the interfaces which will be implemented in our concrete classes.

/* person.interface.ts */
import { IHouse } from "./house.interface";

export interface IPerson {
  getName(): String;
  getHouse(): IHouse;
  getZipCode(): String;
}

/* house.interface.ts */
import { IAddress } from "./address.interface";

export interface IHouse {
  getAddress(): IAddress;
  getColor(): string;
  getSize(): number;
  getZipCode(): string;
}

/* address.interface.ts */
export interface IAddress {
  getZipCode(): string;
  getNumber(): string;
  getStreet(): string;
  getCity(): string;
  getState(): string;
  getCounty(): string;
}

The next step will be the implementation of the concrete classes as you can seen below.

/* person.model.ts */
import { IPerson } from "../interfaces/person.interface";
import { IHouse } from "../interfaces/house.interface";

export class Person implements IPerson {
  private name: string;
  private house: IHouse;

  public constructor(name: string, house: IHouse) {
    this.name = name;
    this.house = house;
  }
  /* Method's are not neccesary to respect Demeter's Law */
  public getName(): string {
    return this.name;
  }
  public getHouse(): IHouse {
    return this.house;
  }
  /**  */

  public getZipCode(): string {
    return this.house.getZipCode();
  }
}
/* house.ts */
import { IHouse } from "../interfaces/house.interface";
import { IAddress } from "../interfaces/address.interface";

export class House implements IHouse {
  private address: IAddress;
  private color: string;
  private size: number;

  public constructor(address: IAddress, color: string, size: number) {
    this.address = address;
    this.color = color;
    this.size = size;
  }
  public getAddress(): IAddress {
    return this.address;
  }

  public getColor(): string {
    return this.color;
  }

  public getSize(): number {
    return this.size;
  }

  public getZipCode(): string {
    return this.address.getZipCode();
  }
}
/* address.ts */
import { IAddress } from "../interfaces/address.interface";

export class Address implements IAddress {
  private zipCode: string;
  private number: string;
  private street: string;
  private city: string;
  private state: string;
  private country: string;

  public constructor(
    zipCode: string,
    number: string,
    street: string,
    city: string,
    state: string,
    country: string
  ) {
    this.zipCode = zipCode;
    this.number = number;
    this.street = street;
    this.city = city;
    this.state = state;
    this.country = country;
  }

  public getZipCode(): string {
    return this.zipCode;
  }

  public getNumber(): string {
    return this.number;
  }

  public getStreet(): string {
    return this.street;
  }

  public getCity(): string {
    return this.city;
  }

  public getState(): string {
    return this.state;
  }

  public getCounty(): string {
    return this.country;
  }
}

The most important in the code is that no method violated Demeter's Law (there is not more than two consecutive invocations of contained objects).

Another example in which the Demeter's Law is broken is the following one:

// Example 2: Violated the Demeter's Law
console.log(
  person
    .getHouse() // return an House's object
    .getAddress() // return an Address's object
    .getZipCode() === "56565656" // return a ZipCode Object
);

// Example 2: Not violate the Demeter's Law
console.log(person.isZipCode("56565656"));

In this case, the solution is implemented isZipCode method in class person which you can see in the following code:

  public isZipCode(zipCode: string): boolean {
    return this.house.getZipCode() === zipCode;
  }

Advantages

The main advantages of satisfying the Demeter's Law are the following:

  1. Dependencies between classes and coupling are reduced.
  2. Reuse the classes with ease.
  3. The code is easier to test.
  4. The code is more maintainable and flexible to changes.

More, more and more

http://www.ccs.neu.edu/home/lieber/LoD.html
https://en.wikipedia.org/wiki/Law_of_Demeter
https://hackernoon.com/the-law-of-demeter-in-the-era-of-microservices-3186f4c399a1
https://testing.googleblog.com/2008/07/breaking-law-of-demeter-is-like-looking.html
http://www.virtuouscode.com/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/
http://www.ccs.neu.edu/home/lieber/LoD/LoD-2011-Zurich.pdf
http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf
https://dzone.com/articles/the-beautiful-law-of-demeter

--
The GitHub branch of this post is https://github.com/Caballerog/blog/tree/master/demeter