Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Law of Demeter
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{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 programming|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,<ref>{{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|url-access=subscription }}</ref> and the following three recommendations serve as a succinct summary:<ref>{{cite web |url=https://github.com/emerleite/demeter |title= README.markdown: Demeter |last = Macedo |first= Emerson |publisher=GitHub |access-date=2012-07-05 }}</ref> # Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. # Each unit should only talk to its friends; don't talk to strangers. # 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 [[top-down and bottom-up design|bottom-up]] philosophy of programming which is also embodied in the law itself.<ref>{{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}}</ref>{{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:<ref>{{cite web |url=http://ccs.neu.edu/home/lieber/what-is-demeter.html |title=The Demeter Project - What is Demeter?}}</ref> {{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 <code>a</code> can request a service (call a method) of an object instance <code>b</code>, but object <code>a</code> should not "reach through" object <code>b</code> to access yet another object, <code>c</code>, to request its services. Doing so would mean that object <code>a</code> implicitly requires greater knowledge of object <code>b</code>'s internal structure. Instead, <code>b</code>'s interface should be modified if necessary so it can directly serve object <code>a</code>'s request, propagating it to any relevant subcomponents. Alternatively, <code>a</code> might have a direct reference to object <code>c</code> and make the request directly to that. If the law is followed, only object <code>b</code> knows its own internal structure. More formally, the Law of Demeter for functions requires that a method <code>m</code> of an object <code>a</code> may only invoke the methods of the following kinds of objects:<ref>{{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 }}</ref> * <code>a</code> itself; * <code>m</code>'s parameters; * any objects instantiated within <code>m</code>; * <code>a</code>'s attributes; * global variables accessible by <code>a</code> in the scope of <code>m</code>. 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".<ref>{{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 }}</ref> That is, the code <code>a.m().n()</code> breaks the law where <code>a.m()</code> 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 [[maintainability|maintainable]] and [[Adaptive reuse|adaptable]]. Since objects are [[Coupling (computer programming)|less dependent]] on the internal structure of other objects, object implementation can be [[Software configuration management|changed]] without reworking their callers. Basili et al.<ref name=Basili>{{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 }}</ref> 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 bug]]s. Following the Law of Demeter can result in a lower RFC. However, the results also suggest that an increase in ''Weighted Methods per Class''<ref>{{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}}</ref> (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 (object-oriented design)|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 method]]s to propagate calls to components; in some cases, this can add noticeable time and space overhead.<ref name=Basili/><ref name=BradApp>{{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).}}</ref><ref name=Pragmatic>{{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.}}</ref> 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.<ref>{{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 }}</ref> 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.<ref name=BradApp/><ref name=Pragmatic/> 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 programming|aspect-oriented]] approach,<ref name=AOP-Programming>{{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 }}</ref> 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== * [[Facade pattern]] * [[Principle of least astonishment]] * [[Single-responsibility principle]] ==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}} ==External links== *[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/general-formulation.html Law of Demeter (LoD)] *[http://www.ccs.neu.edu/research/demeter/papers/law-of-demeter/oopsla88-law-of-demeter.pdf "Object-Oriented Programming: An Objective Sense of Style" (OOPSLA '88 Proceedings) (PDF)] *[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet, and The Law Of Demeter (PDF)] *[http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx Phil Haack: "The Law of Demeter is not a Dot Counting Exercise"] *[http://www.ccs.neu.edu/home/lieber/LoD.html Lieber: "Law of Demeter: Principle of Least Knowledge"] *[http://www.ccs.neu.edu/research/demeter/biblio/dem-book.html "Adaptive Object-Oriented Software, The Demeter Method"] *[http://ccs.neu.edu/home/lieber/what-is-demeter.html The Demeter Project β- What is Demeter?] [[Category:Object-oriented programming]] [[Category:Programming principles]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Blockquote
(
edit
)
Template:Cite book
(
edit
)
Template:Cite journal
(
edit
)
Template:Cite web
(
edit
)
Template:Non-primary source needed
(
edit
)
Template:Refbegin
(
edit
)
Template:Refend
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)