The Law of Demeter

Before we delve into the SOLID arena, it's useful to explore a less well-known principle, known as LoD, or the principle of least knowledge. This so-called law has three core ideas:

  • A unit should have only limited knowledge about other units
  • A unit should only talk to its immediate friends
  • A unit should not talk to strangers

You may rightfully wonder what it means for a unit to talk to a stranger. A unit, in this context, is a specific coded abstraction: possibly a function, a module, or a class. And talking here means interfacing with, such as calling the code of another module or having that other module call your code.

This is a very useful and simple law to learn and then apply to all our programming, whether we're ...

Get Clean Code in JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.