Law of Demeter

{{Short description|Design guideline for software development}}

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed by Ian Holland at Northeastern University towards the end of 1987,{{Cite journal |last1=Lieberherr |first1=K.J. |last2=Holland |first2=I.M. |date=September 1989 |title=Assuring good style for object-oriented programs |url=http://dx.doi.org/10.1109/52.35588|journal=IEEE Software |volume=6 |issue=5 |pages=38–48 |doi=10.1109/52.35588 |s2cid=12651917 |issn=0740-7459}} and the following three recommendations serve as a succinct summary:{{cite web |url=https://github.com/emerleite/demeter |title= README.markdown: Demeter |last = Macedo |first= Emerson |publisher=GitHub |access-date=2012-07-05

}}

  1. Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
  2. Each unit should only talk to its friends; don't talk to strangers.
  3. 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), in accordance with the principle of "information hiding". It may be viewed as a corollary to the principle of least privilege, which dictates that a module possess only the information and resources necessary for its legitimate purpose.

It is so 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 goddess of agriculture, to signify a bottom-up philosophy of programming which is also embodied in the law itself.{{Cite web |title=Law of Demeter: Principle of Least Knowledge |url=https://www.khoury.northeastern.edu/home/lieber/LoD.html |access-date=2024-11-07 |website=www.khoury.northeastern.edu}}{{Non-primary source needed|date=November 2024}}

History

The law of Demeter dates back to 1987 when it was first proposed by Ian Holland, who was working on the Demeter Project. This project was the birthplace of a lot of aspect-oriented programming (AOP) principles.

A quote in one of the remainders of the project seems to clarify the origins of the name:{{cite web |url=http://ccs.neu.edu/home/lieber/what-is-demeter.html |title=The Demeter Project - What is Demeter?}}

{{Blockquote

|text=Demeter

The Greek goddess of Agriculture.

The Demeter project was named after Demeter because we were working

on a hardware description language Zeus and we were looking for a tool

to simplify the implementation of Zeus. We were looking for a tool name

related to Zeus and we chose a sister of Zeus: Demeter.

We later promoted the idea that Demeter-style software development is

about growing software as opposed to building software.

We introduced the concept of a growth plan which is basically

a sequence of more and more complex UML class diagrams.

Growth plans are useful for building systems incrementally.

}}

In object-oriented programming

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, c, to request its services. Doing so would mean that object a implicitly requires greater knowledge of object b's internal structure.

Instead, b's interface should be modified if necessary so it can directly serve object a's request, propagating it to any relevant subcomponents. Alternatively, a might have a direct reference to object c and make the request directly to that. If the law is followed, only object b knows its own internal structure.

More formally, the Law of Demeter for functions requires that a method m of an object a may only invoke the methods of the following kinds of objects:{{cite web

| title = The Paperboy, The Wallet, and The Law Of Demeter

| url = http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf

| last = Bock

| first = David

| page = 5

| publisher = College of Computer and Information Science, Northeastern University

| access-date = 2012-07-05

}}

  • a itself;
  • m's parameters;
  • any objects instantiated within m;
  • a's attributes;
  • global variables accessible by a in the scope of m.

In particular, an object should avoid invoking methods of an object returned by another method. For many modern object-oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot".{{cite book |page=81 |title=Practical Object-Ortiented Design: An Agile Primer Using Ruby |first=Sandi |last=Metz |edition=Second |publisher=Addison-Wesley |year=2019 |isbn=978-0134456478 |lccn=2018939833 }} That is, the code a.m().n() breaks the law where a.m() does not. As an analogy, when one wants a dog to walk, one does not command the dog's legs to walk directly; instead, one commands the dog which then commands its own legs.

Advantages

The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object implementation can be changed without reworking their callers.

Basili et al.{{cite journal

| first1=Victor

| last1=Basili

| first2=L.

| last2=Briand

| first3=W. L.

| last3=Melo

| date=October 1996

| title=A Validation of Object-Oriented Design Metrics as Quality Indicators

| journal=IEEE Transactions on Software Engineering

| volume=22

| issue=10

| pages=751–761

| quote=As expected, the larger the WMC, the larger the probability of fault detection.

| doi=10.1109/32.544352

| url=http://drum.lib.umd.edu/bitstream/1903/715/2/CS-TR-3443.pdf

| hdl=1903/715

| hdl-access=free

}} published experimental results in 1996 suggesting that a lower Response For a Class (RFC, the number of methods potentially invoked in response to calling a method of that class) can reduce the probability of software bugs. Following the Law of Demeter can result in a lower RFC. However, the results also suggest that an increase in Weighted Methods per Class{{Cite web|url=https://maisqual.squoring.com/wiki/index.php/Weighted_Methods_per_Class|title=Weighted Methods per Class - Maisqual Wiki|website=maisqual.squoring.com|language=en|access-date=2018-09-20}} (WMC, the number of methods defined in each class) can increase the probability of software bugs. Following the Law of Demeter can also result in a higher WMC.

A multilayered architecture can be considered to be a systematic mechanism for implementing the Law of Demeter in a software system.

In a layered architecture, code within each layer can only make calls to code within the layer and code within the next layer down.

"Layer skipping" would violate the layered architecture.

Disadvantages

Although the LoD increases the adaptiveness of a software system, it may result in having to write many wrapper methods to propagate calls to components; in some cases, this can add noticeable time and space overhead.{{cite web |url=http://www.bradapp.com/docs/demeter-intro.html |title=Introducing Demeter and its Laws | last=Appleton | first=Brad |access-date=6 July 2013 |quote=A side-effect of this is that if you conform to LoD, while it may quite increase the maintainability and "adaptiveness" of your software system, you also end up having to write lots of little wrapper methods to propagate methods calls to its components (which can add noticeable time and space overhead).}}{{cite web |url=http://pragprog.com/articles/tell-dont-ask |title=Tell, Don't Ask |publisher=The Pragmatic Programmers, LLC |access-date=6 July 2013 |quote=The disadvantage, of course, is that you end up writing many small wrapper methods that do very little but delegate container traversal and such. The cost tradeoff is between that inefficiency and higher class coupling.}}

At the method level, the LoD leads to narrow interfaces, giving access to only as much information as it needs to do its job, as each method needs to know about a small set of methods of closely related objects.{{cite book

| chapter-url = http://www.ccs.neu.edu/research/demeter/papers/law-of-demeter/oopsla88-law-of-demeter.pdf

| title = Conference proceedings on Object-oriented programming systems, languages and applications (OOPSLA '88)

| chapter = Object-Oriented Programming: An Objective Sense of Style

| last1 = Lieberherr

| first1 = K.

| last2 = Holland

| first2 = I.

| last3 = Riel

| first3 = A.

| date = 1988

| publisher = ACM |pages=323–334 |doi=10.1145/62083.62113 |editor-first=Norman |editor-last=Meyrowitz

| quote = Easier software maintenance, less coupling between your methods, better information hiding, narrower interfaces, methods which are easier to reuse, and easier correct.ness proofs using structural induction.

| access-date = 2012-07-05

| isbn = 978-0897912846

| s2cid = 562521

}} On the other hand, at the class level, if the LoD is not used correctly, wide (i.e., enlarged) interfaces may be developed that require introducing many auxiliary methods. This is due to poor design rather than a consequence of the LoD per se. If a wrapper method is being used, it means that the object being called through the wrapper should have been a dependency in the calling class.

One proposed solution to the problem of enlarged class interfaces is the aspect-oriented approach,{{cite journal

|last1 = Lieberherr

|first1 = Karl

|last2 = Orleans

|first2 = Doug

|last3 = Ovlinger

|first3 = Johan

|date = October 2001

|title = Aspect-oriented programming with adaptive methods

|pages = 39–40

|journal = Commun. ACM

|volume = 44

|issue = 10

|doi = 10.1145/383845.383855

|quote = An adaptive method encapsulates the behavior of an operation into one place, thus avoiding the scattering problem, but also abstracts over the class structure, thus avoiding the tangling problem as well.

|citeseerx = 10.1.1.192.6403

|s2cid = 2792493

}} where the behavior of the method is specified as an aspect at a high level of abstraction. The wide interfaces are managed through a language that specifies implementations. Both the traversal strategy and the adaptive visitor use only a minimal set of classes that participate in the operation, and the information about the connections between these classes is abstracted out.

See also

References

{{reflist|2}}

Further reading

{{refbegin}}

  • {{cite journal |first1=Karl |last1=Lieberherr |first2=I. |last2=Holland |date=September 1989 |title=Assuring good style for object-oriented programs |journal=IEEE Software |pages=38–48 |doi=10.1109/52.35588 |volume=6 |issue=5|s2cid=12651917 }}
  • {{cite book |last=Lieberherr |first=Karl J. |year=1995 |title=Adaptive Object-Oriented Software: The Demeter Method with Propagation Patterns |url=https://archive.org/details/adaptiveobjector0000lieb |url-access=registration |publisher=PWS Publishing Company |isbn=978-0534946029}}
  • {{cite book |first1=Andrew |last1=Hunt |first2=David |title=The Pragmatic Programmer: From Journeyman to Master |publisher=Addison-Wesley |year=2002 |pages=140–1 |chapter=5. Bend, or Break § The Law of Demeter for Functions|last2=Thomas |chapter-url=https://books.google.com/books?id=5wBQEp6ruIAC&pg=PA140 |isbn=978-0-13-211917-7 }}
  • {{cite book |last=Larman |first=Craig |title=Applying UML and Patterns |publisher=Prentice Hall |year=2005 |edition=3rd |pages=430–2 |author-link=Craig Larman}} (from this book, "Law of Demeter" is also known as "Don't talk to strangers")
  • {{cite book |last=McConnell |first=Steve |title=Code Complete |url=https://archive.org/details/codecomplete0000mcco |url-access=registration |publisher=Microsoft Press |year=2004 |edition=2nd |pages=[https://archive.org/details/codecomplete0000mcco/page/150 150] |isbn=9780735619678 |author-link=Steve McConnell}}
  • {{cite book|title=ASP.NET MVC in Action|publisher=Manning Publications|year=2009|pages=14|first1=Jeffrey |last1=Palermo |first2=Ben |last2=Scheirman |first3=Jimmy |last3=Bogard}}

{{refend}}