oopencapsulationlaw-of-demeter

Encapsulation Principle


There's some object-oriented engineering principle that states something along the lines of "a class should only know about the contracts of the classes that it takes as arguments, or any internal ones it uses."

The counter-example, in C++, is:

Foo::bar( Baz* baz)
{
  baz()->blargh()->pants()->soil();  // this is bad, Foo knows about blarghs and pants
}

Does this principle have a name? Also, the actual principle rather than my paraphrase above would be nice to see.


Solution

  • The law of demeter thanks to Jim Burger says:

    The Law of Demeter (LoD), or Principle of Least Knowledge, is a design guideline for developing software, particularly object-oriented programs. The guideline was invented at Northeastern University towards the end of 1987, and can be succinctly summarized as “Only talk to your immediate friends.” The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).