liveBook · Manning

Law of Demeter

As explained in Object-Oriented Software Design in C++

The Law of Demeter is a software design principle that limits how much implementation knowledge and object-structure navigation a component exposes or relies upon.

The Law of Demeter, also called the Principle of Least Knowledge, limits a class’s dependencies by hiding implementation details and exposing only what other code needs. Private members make hidden implementation inaccessible, so internal changes need not force changes elsewhere. section 5.1

A member function may call another object’s function when the object is:

  • Aggregated by the calling class. section 5.6
  • Passed as an argument to the calling function. section 5.6
  • Instantiated by the calling function. section 5.6
  • Not merely returned by another object’s member function; navigating that returned object creates a problematic dependency. section 5.6

Automobile maintenance

In the DemeterAuto example, Engine replaces its own Sparkplug, and DemeterAuto can pass a Sparkplug to service_sparkplug or create one locally. Calling get_sparkplug and then replacing the returned plug violates the law; engine.replace_sparkplug preserves the boundary. section 5.6

How Object-Oriented Software Design in C++ covers it

How deep it goes
Defines four legal call relationships and connects them to private members, encapsulation, and change isolation.
Examples
Uses C++ classes named DemeterAuto, Engine, and Sparkplug to contrast direct calls with returned-object navigation.
What it assumes
Assumes familiarity with classes, member functions, member variables, arguments, and object creation.
What you can do after
Apply it to expose necessary behavior while avoiding calls through objects returned by other objects.
How it connects
Connects implementation hiding, encapsulation, the Principle of Least Knowledge, loose coupling, and the Open-Closed Principle.

Also explained in

Compare how 2 books explain Law of Demeter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.