Skip to content

Instantly share code, notes, and snippets.

@dimabory
Last active February 11, 2019 09:20
Show Gist options
  • Save dimabory/1f83c4f4ff582e192e79106b74d04810 to your computer and use it in GitHub Desktop.
Save dimabory/1f83c4f4ff582e192e79106b74d04810 to your computer and use it in GitHub Desktop.
Law of Demeter
  • Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  • Each unit should only talk to its friends; don't talk to strangers.
  • Only talk to your immediate friends.

https://www2.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf

More formally, the Law of Demeter for functions requires that a method m of an object O may only invoke the methods of the following kinds of objects:

  1. O itself
  2. m's parameters
  3. Any objects created/instantiated within m
  4. O's direct component objects
  5. A global variable, accessible by O, in the scope of m

In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method() breaks the law where a.Method() does not. As an analogy, when one wants a dog to walk, one does not command the dog's legs to walk directly; instead one commands the dog which then commands its own legs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment