object orientation – What is the Law of Demetrius about?


In a competition test, I found the following question:

In Object Oriented Programming, the law of Demetrius ( Law of Demeter ) says that a method m of an object O must not invoke methods of the following types of objects: (A) of O itself. (B) parameters of m. (C) any object created/instantiated in m. (D) objects returned by calling other methods. (E) attributes of O. ( Specific Knowledge – System Analyst – q54 – 2013 )

Among these, the correct answer would be " (C) any object created/instantiated in m " according to the template.

What is this so-called Law of Demetrius?


There is a translation error there.

From Wikipedia about the law:

It is named for its origin in the Demeter Project, an adaptive programming and aspect-oriented programming effort. The project was named in honor of Demeter, "distribution-mother" and the Greek god dess of agriculture.

It is the name of the Goddess Demeter, or Demetra.

Other than that, the law says that a code unit must know and communicate only with the units closest to it and that are directly related to it. Again from the wiki:

When applied to object-oriented programs(…) an object A can request a service (call a method) of an object instance B, but object A should not "reach through" object B to access yet another object

"When applied to OO (…) object A can request a service (call a method) of an instance of object B, but object A cannot "walk through" object B to access a third object."

In your case, method "m" can access its parent (type "O"), its siblings (other members of "O"), its own parameters, and so on. The law is violated if "m" accesses other objects that were created by other methods, ie alternative D .

Scroll to Top