Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Law of Demeter


The Demeter Law is a good practice for object-oriented programming focused on reducing the coupling between classes.

Probably sound the following way to retrieve information from an object:

System.out.println(university.getDepartment(“Department of Information Technology”).getSubject(“Software engineering”).getProfesorCoordinador());

As you can see, in this case a University object does not have first level access to the coordinating teacher of a subject. This implies that you have to make a third level call to a subject Subject to retrieve the desired coordinating teacher. In this way, the object of type University is being given information about the structure of the Subject type, to which it does not have direct access, and in addition, it is trusting how that third party provides the information.

What does the Demeter Law say?

The foundation of the Demeter Law is as follows:

For all classes, C, and for all methods, M, contained in C, all objects to which M sends a message must be instances of associated classes in the following way:

      • The classes that define the arguments of M, including C
      • The classes that define the attributes of C

It is considered that the objects created by M, or by methods that are called from M, and the global variables are arguments of M.

What is the purpose of the Demeter Law?

The main objective of the Demeter Act is to reduce the coupling between classes, resulting in an improvement in code maintenance. It does so by decreasing the level of dependency that a class has with respect to the internal structure of another class that it does not know because it is not a “known” one of its kind.

In the previous example, if for some reason the behavior of the getProfesorCoordinador () method or its interface is modified, or even if the Subject class is omitted, it is necessary to recode the call stack. In the example, it would not be expensive, but what would happen if, on a real project, this type of recoding has to be done repeatedly, and not just for one case, but for several?

When applying the Demeter Law, we will recover the name of the coordinating teacher of a subject in this way

in this way:

The post Law of Demeter appeared first on Target Veb.

This post first appeared on Targetveb, please read the originial post: here

Share the post

Law of Demeter


Subscribe to Targetveb

Get updates delivered right to your inbox!

Thank you for your subscription