views:

472

answers:

4

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.

+5  A: 

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).
Steven A. Lowe
http://en.wikipedia.org/wiki/Law_of_Demeter
Jim Burger
@[Jim Burger]: thanks, answer edited to include link and quote
Steven A. Lowe
Uh, it is Jim, not Kim. Anyway, this does not only apply to object oriented programming.
Svante
@[Harleqin]: oops! typo fixed.
Steven A. Lowe
A: 

That may or may not compile (due to the parentheses after the baz pointer), but your example breaks at least one principle that I can think of. It breaks the Law of Demeter (also called the Law of Parsimony, I believe). The main principles can be found here: S.O.L.I.D. Principles

Aside from these, I'm not sure if there is a specific name for what you're describing. You can look up the Law of Demeter on wikipedia.

A: 

Look at Robert Martin's SOLID principles. Specifically, look at the Single responsibility Principle. The complex chain of dependencies in your example looks like it breaks the SRP.

Encapsulation -- itself -- isn't a principle. It's part of achieving the various principles. Along with inheritance, polymorphism and other more obscure OO features.

S.Lott
A: 

I would say here that good encapsulation helps to reduce coupling - - which is a good goal for any decent encapsulation apart from the obvious.

LenW