Member-only story

Law of Demeter

Park Sehun
4 min readJul 22, 2023

Ref: Clean Code

The Law of Demeter (LoD) or principle of the least knowledge is a design guideline for developing software, particularly object-oriented programs. The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents), in accordance with the principle of “information hiding”. It may be viewed as a result of the least privilege principle, which dictates that a module possesses only the information and resources necessary for its legitimate purpose. (…from wiki)

https://blog.knoldus.com/the-law-of-demeter/

Example

Example of violating the Law of Demeter:

class Customer {
private ShoppingCart cart;

public void checkout() {
Inventory inventory = new Inventory();
inventory.update(cart.getItems()); // violates Law of Demeter
}
}

Explanation: the Customer object should NOT have knowledge of the Inventory object.

Example of applying the Law of Demeter:

class Customer {
private ShoppingCart cart;

public void checkout() {
cart.checkout();
}
}

class ShoppingCart {
private List<Item> items;

public void checkout() {
Inventory inventory = new Inventory();
inventory.update(items);
}
}

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response