Monthly Archives: July 2011

The Law of Demeter

Let’s talk about OO design.

Have you heard of the Law of Demeter? If you develop software, you should. You may actually be familiar with its concepts without actually knowing that it had a formal name. At it’s core, the Law of Demeter is the explicit capture of the intent of encapsulation. The rules are as follows.

A method FooMethod of a class Foo should only call the methods of these:

  • Foo
  • An object created by FooMethod
  • An object passed as an argument to FooMethod
  • An object reference held as an instance variable of Foo

Uncle Bob summarizes it nicely: “In other words, talk to friends, not to strangers.”

It’s easy to forget this when dealing with complicated designs, or designs that are poorly understood.

Happy coding.