Law Of Demeter - Don't Depend On Strangers
Topic | Source |
---|---|
๐งน Clean Code | Clean Code - Udemy |
The Law of Demeter is defined by the Principle of Least Knowledge: Don't depend on the internals of "strangers" (other **objects which you don't directly know).
What this infers, is that you should not access deeply nested properties, e.g. this.customer.lastPurchase.date
.
You should only access data, that
- belongs to the object
- are stored as properties of that object
- are received as method parameters
- created in the method
To avoid this, tell, don't ask.
Pass in the appropriate parameters into functions to access those properties.
// this is bad
const date = this.customer.lastPurchase.date; // breaking law of demeter
this.warehouse.deliverPurchasesByDate(this.customer, date);
// better
const date = this.customer.getLastPurchaseDate(); // you could define a getter to avoid this
this.warehouse.deliverPurchasesByDate(this.customer, date);
// best
this.warehouse.deliverPurchase(this.customer.lastPurchase);