The Law of Demeter

A post about the Law of Demeter

Nathaniel Saul

2 minute read

The Law of Demeter is a small set of rules for how objects should interact with each other. It helps define the boundaries between objects and determine who controls and owns what. Applying this design principle gives each object their own personal space and keeps objects from micromanaging others.

The rules

The LoD provides actionable and quantifiable rules for structuring software that help enable the SOLID principles. It defines what methods and variables an object is allowed to call.

LoD is a concrete design pattern that aids in following the SOLID principles.

An object can call methods that are apart of

  1. the same object.
  2. a parameter passed into the method.
  3. a object created within its method.
  4. an object it owns.
  5. a global variable.

This implies that any action this object takes must be by manipulating objects of no more than 1 degree away from it. A parent can tell their children what to do, but are not allowed to tell their grandchildren what to do. A manager should manage their direct subordinates, but definitely not manage their subordinates subordinates.

Software Lamination

The Law of Demeter explicitly improves software lamination.

Laminated software is when software clearly separates into layers, similar to filo dough. [baking show lamination reference plz]. This idea deserves an entire blog post in its own.

This practice keeps objects on their respective layers, only manipulating objects on their own layer, or one layer above and below them. This deters leaky abstractions from seeping into your code.

SOLID principles

What I like about the Law of Demeter is how nicely it wraps up many other practices of object oriented design. It enforces proper encapsulation by isolating changes in subobjects. This in turn helps to create better models of real world objects by putting pressure on the developer to improve interface design.

  • Single Responsibility Principle:
    • “have only one reason for change” - Breaking the Law of Demeter breaks the SRP because when a subobject changes, your object would have to change also.
  • Dependency Inversion:
    • “depend upon abstractions, not concretions” - so by not reaching into the guts of an object, you are forces to depend on an abstraction, not the nitty gritty details of the object.
,