Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Law of Demeter is very confusing because looks like I couldn't ever write methods that return objects

It feels like I've come to a dead end. If I understood it right then if I follow the Law of Demeter I can never make a method that returns an object and then client code makes calls to it. I'm just thinking about the Factory Pattern which always returns an object. Yes, there are mapper classes that return objects. And how about collections?

like image 461
PPPHP Avatar asked Feb 19 '11 09:02

PPPHP


People also ask

What is one way of describing the Law of Demeter?

The Law of Demeter (or the Principle of Least Knowledge) is a design guideline for developing software applications. First discussed at the Northeastern University in 1987, this principle states that an object should never know the internal details of other objects.

Why is the Law of Demeter called that?

The name of the law references the name of the project the authors were coding when they coined it. The authors named the project “Demeter”, which itself is a reference to a hardware description language called “Zeus”. Demeter, the goddess of harvest and agriculture, is a sister of Zeus.

What is the Law of Demeter trying to prevent?

The Law of Demeter asks us to minimize coupling between classes and avoid reaching out to the third object in order in order to make refactoring and developing new features easily.

Which proposed the Law of Demeter?

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. This law was proposed by Ian Holland in 1987. Holland and colleagues were programming a system called Demeter using oriented object programming.


1 Answers

You've misunderstood the Law of Demeter and are applying it beyond the point of usefulness:

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:

  • O itself
  • M's parameters
  • any objects created/instantiated within M
  • O's direct component objects
  • a global variable, accessible by O, in the scope of M

Factories in particular are used to create an object, and the type of object they create is part of their public interface. Thus, calling methods of an object created by a factory is allowed by the above.

like image 198
Thomas Edleson Avatar answered Oct 26 '22 08:10

Thomas Edleson