Law of Demeter

What is the Law of Demeter

- It is a design guideline for developing software

- It is a technique to achieve loose coupling

- It's considered a good design technique, often applied in OOP

- A.K.A principle of least knowledge

Guidelines

- Each object should have only limited knowledge about others

- Each object should only talk to its friends, don't talk to strangers

- Only talk to your immediate friends

Not compliant

Compliant (single dot)

Not compliant (single dot)

                                 Don't lie to yourself!

Not compliant (single dot)

                                 Don't lie to yourself!

Compliant (multiple dots)

- Account only talks to Plan

Example

- Lets suppose we have to refactor the domain model

Users might not have a profile, and the plan belongs to the profile

Example

- And we have code like this...

Example

- We will have to make changes in multiple places

If we would have followed Demeter

- We only need to make a change in one class (The User class)

So the model would look like this

And the services don't need to change

Requirements

- 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

A method m of an object O may only invoke the methods of the following kinds of objects

Summary

We don’t want our functions to know about an entire object graph

 

Individual functions should have a limited amount of knowledge

 

We want to tell our neighbor objects what we need to have done and depend on them to propagate that message outwards to the appropriate destination

QA?

PPA - Tech huddle (Demeter law)

By David Molinero

PPA - Tech huddle (Demeter law)

  • 138