Law of Demeter

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,[1] and the following three recommendations serve as a succinct summary:[2]

  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.[3][non-primary source needed]

History

The law 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:[4]

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:[5]

  • 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".[6] 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.[7] 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[8] (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.[7][9][10]

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.[11] 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.[9][10] 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,[12] 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

  1. ^ Lieberherr, K.J.; Holland, I.M. (September 1989). "Assuring good style for object-oriented programs". IEEE Software. 6 (5): 38–48. doi:10.1109/52.35588. ISSN 0740-7459. S2CID 12651917.
  2. ^ Macedo, Emerson. "README.markdown: Demeter". GitHub. Retrieved 2012-07-05.
  3. ^ "Law of Demeter: Principle of Least Knowledge". www.khoury.northeastern.edu. Retrieved 2024-11-07.
  4. ^ "The Demeter Project - What is Demeter?".
  5. ^ Bock, David. "The Paperboy, The Wallet, and The Law Of Demeter" (PDF). College of Computer and Information Science, Northeastern University. p. 5. Retrieved 2012-07-05.
  6. ^ Metz, Sandi (2019). Practical Object-Ortiented Design: An Agile Primer Using Ruby (Second ed.). Addison-Wesley. p. 81. ISBN 978-0134456478. LCCN 2018939833.
  7. ^ a b Basili, Victor; Briand, L.; Melo, W. L. (October 1996). "A Validation of Object-Oriented Design Metrics as Quality Indicators" (PDF). IEEE Transactions on Software Engineering. 22 (10): 751–761. doi:10.1109/32.544352. hdl:1903/715. As expected, the larger the WMC, the larger the probability of fault detection.
  8. ^ "Weighted Methods per Class - Maisqual Wiki". maisqual.squoring.com. Retrieved 2018-09-20.
  9. ^ a b Appleton, Brad. "Introducing Demeter and its Laws". Retrieved 6 July 2013. 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).
  10. ^ a b "Tell, Don't Ask". The Pragmatic Programmers, LLC. Retrieved 6 July 2013. 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.
  11. ^ Lieberherr, K.; Holland, I.; Riel, A. (1988). "Object-Oriented Programming: An Objective Sense of Style" (PDF). In Meyrowitz, Norman (ed.). Conference proceedings on Object-oriented programming systems, languages and applications (OOPSLA '88). ACM. pp. 323–334. doi:10.1145/62083.62113. ISBN 978-0897912846. S2CID 562521. Retrieved 2012-07-05. 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.
  12. ^ Lieberherr, Karl; Orleans, Doug; Ovlinger, Johan (October 2001). "Aspect-oriented programming with adaptive methods". Commun. ACM. 44 (10): 39–40. CiteSeerX 10.1.1.192.6403. doi:10.1145/383845.383855. S2CID 2792493. 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.

Further reading

Read other articles:

Gambar Kumparan Pengapian Kumparan pengapian, atau lebih dikenal sebagai ignition coil adalah sistem kumparan yang berfungsi untuk mengubah tegangan primer dari baterai kendaraan bemotor menjadi tegangan sekunder sebesar 15000 - 30000 volt yang cukup kuat untuk membantu pengapian motor. Cara kerja Saat kunci starter diputar ke tanda on sumbu Nr. 15 (angka 15 menunjukkan kode elektrik di Eropa utk sumbu positif yg dinyalakan) akan terhubung dengan baterai. Pada saat ini siklus listrik akan men...

 

Bože pravdeLagu kebangsaan  SerbiaPenulis lirikJovan Đorđević, 1872KomponisDavorin Jenko, 1872Sampel audioBože pravde (Instrumen)berkasbantuan Sampel audioBože pravdeberkasbantuan Bože pravde (Serbia: Боже правде, Inggris: God of Justice) merupakan lagu kebangsaan resmi Serbia dan Republika Srpska. Lagu ini diciptakan pada tahun 1872 dengan musik oleh Davorin Jenko dan lirik oleh Jovan Đorđević. Selama menjadi lagu kebangsaan Kerajaan Serbia, lirik aslinya memuja raja...

 

Cet article est une ébauche concernant la société. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Pour les articles homonymes, voir La Grand-Croix. Le terme grand-croix[1] (grand'croix est une graphie archaïque toujours utilisée par le Journal officiel de la République française[2] ou les ordres eux-mêmes[3]) désigne la dignité (mais aussi le récipiendaire lui-même) la plus élevée de certains ordr...

Australian cyclist Kaarle McCullochPersonal informationBorn (1988-01-20) 20 January 1988 (age 36)Campbelltown, New South Wales, AustraliaHeight1.68 m (5 ft 6 in)[1]Weight70 kg (154 lb)Team informationDisciplineTrackRoleRiderRider typeSprinter Medal record Women's track cycling Representing  Australia Olympic Games 2012 London Team sprint World Championships 2009 Pruszków Team sprint 2010 Ballerup Team sprint 2011 Apeldoorn Team sprint 2019 Prus...

 

Vehicle containing a pivotal joint Articulated redirects here. For other uses, see Articulation (disambiguation). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Articulated vehicle – news · newspapers · books · scholar · JSTOR (September 2017) (Learn how and when to remove this template message) An articula...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يناير 2017) ڤينموراسومعلومات عامةالمؤلف جياموهاناللغة لغة تاميليةالعنوان الأصلي ڤينموراسوالبلد الهندالنوع الأدبي واقعيةالشكل الأدبي رواية تاريخ الإصدار 2014التقديمن...

Part of a series onBritish law Acts of Parliament of the United Kingdom Year      1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 ...

 

Artikel ini bukan mengenai Harper's Magazine, Harper's Bazaar, atau Harpers Magazine (publikasi dagang). Harper's WeeklySampul Harper's Weekly menampilkan Presiden-Terpilih Abraham Lincoln; ilustrasi karya Winslow Homer dari sebuah foto buatan Mathew Brady (10 November 1860)Ilustrator Winslow Homer Livingston Hopkins Thomas Nast Granville Perkins Theodore R. Davis KategoriBerita, politikFrekuensiMingguanPendiriFletcher HarperDidirikan1857 (1857)Terbitan pertama3 Januari 1857 (1857-J...

 

Cet article est une ébauche concernant un homme politique. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Pour les articles homonymes, voir Ali ben Yusuf. Ali ibn Jusufas ZakarijaBiographieDécès 1458Activité Homme politiquemodifier - modifier le code - modifier Wikidata `Alî ben Yûsuf[1] succéda à son oncle[2] Abû Zakarîyâ Yahyâ comme vizir et régent watasside du sultan mérinide Abû Muhammad `Abd...

Indian cricketer (born 1949) Sunil GavaskarGavaskar in 2012Sheriff of MumbaiIn office1995-1996Preceded byI. M. KadriSucceeded bySubir Kumar Choudhury Personal informationFull nameSunil Manohar GavaskarBorn (1949-07-10) 10 July 1949 (age 74)Bombay, Province of Bombay, IndiaNicknameSunny, Little MasterHeight5 ft 4 in (163 cm)[1]BattingRight-handedRoleOpening batsmanRelationsMadhav Mantri (uncle)Manohar Gavaskar (father)Meenal Gavaskar (mother)Marshneil Gavaskar ...

 

Alex Valentini Nazionalità  Italia Altezza 186 cm Peso 80 kg Calcio Ruolo Portiere Squadra  Crotone CarrieraGiovanili ????-2005 MantovaSquadre di club1 2005-2007 Mantova0 (0)2007-2009→  Sambonifacese55 (-29+)2009-2010 Mantova0 (0)2010 Pro Sesto14 (-22)2010-2013 Pro Vercelli104 (-104)[1]2013-2014 Spezia4 (-7)2014-2015→  Cittadella23 (-34)2015-2016→  Lugano11 (-29)2016-2017 Spezia0 (0)2017-2018 Vicenza34 (-39)[...

 

Questa voce sull'argomento contee dell'Illinois è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Contea di MassacconteaLocalizzazioneStato Stati Uniti Stato federato Illinois AmministrazioneCapoluogoMetropolis Data di istituzione1843 TerritorioCoordinatedel capoluogo37°13′12″N 88°42′36″W / 37.22°N 88.71°W37.22; -88.71 (Contea di Massac)Coordinate: 37°13′12″N 88°42′36″W / 37.22°N 88.71°...

Pour les articles homonymes, voir Barrême (homonymie). Hôtel de BarrêmeAngle des rues Barrême & Frédéric MistralPrésentationType Hôtel particulierConstruction 1646Propriétaire PrivéPatrimonialité  Classé MH (1988)LocalisationPays FranceRégion Provence-Alpes-Côte d'AzurDépartement Bouches-du-Rhône (13)Commune ArlesCoordonnées 43° 40′ 38″ N, 4° 37′ 34″ ELocalisation sur la carte des Bouches-du-RhôneLocalisation sur la cart...

 

Voce principale: Calcio Lecco 1912. Associazione Calcio LeccoStagione 1952-1953Sport calcio Squadra Lecco Allenatore Hugo Lamanna Presidente Mario Ceppi IV Serie1º nel girone B, promosso in Serie C. Maggiori presenzeCampionato: Corradi (38) Miglior marcatoreCampionato: Bicicli, Vecchio (12) StadioStadio Mario Rigamonti 1951-1952 1953-1954 Si invita a seguire il modello di voce Questa pagina raccoglie le informazioni riguardanti l'Associazione Calcio Lecco nelle competizioni ufficiali d...

 

Pour les articles homonymes, voir Udall. Stewart Lee Udall Fonctions 37e secrétaire à l'Intérieur des États-Unis 21 janvier 1961 – 20 janvier 1969(7 ans, 11 mois et 30 jours) Président John Fitzgerald KennedyLyndon B. Johnson Gouvernement Administration KennedyAdministration L.B. Johnson Prédécesseur Fred Andrew Seaton Successeur Walter Hickel Représentant des États-Unis 3 janvier 1955 – 21 janvier 1961(6 ans et 18 jours) Circonscription 2e district...

This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Nookala Chinna Satyanarayana – news · newspapers · books · scholar · JSTOR (March 2008) (Learn how and when to remove this message) Nookala Chinna SatyanarayanaBackground informationBorn(1923-08-04)4 August 1923OriginAnakapalli, Andhra Pradesh, IndiaDied11 July 2013(2013-07-11) (aged 89)GenresCarnati...

 

جمهورية مصر العربيةوزارة الدفاع المصريةجهاز الصناعات والخدمات البحرية تفاصيل الوكالة الحكومية البلد مصر  الاسم الكامل جهاز الصناعات والخدمات البحرية تأسست 2003  المركز الإسكندرية،  مصر الإدارة المدير التنفيذي لواء بحري أركان حرب / محمد أحمد محمود، مدير جهاز الصنا...

 

Amersfoortcomune Amersfoort – VedutaVeduta LocalizzazioneStato Paesi Bassi Provincia Utrecht AmministrazioneCapoluogoAmersfoort SindacoLucas Bolsius (CDA) TerritorioCoordinatedel capoluogo52°09′23″N 5°23′23″E52°09′23″N, 5°23′23″E (Amersfoort) Altitudine3 m s.l.m. Superficie63,86 km² Abitanti154 712 (2017) Densità2 422,67 ab./km² Altre informazioniCod. postale3800–3829 Prefisso033 Fuso orarioUTC+1 Codice CBS0307 Nome abitantiAm...

Inscription from Central Java, Indonesia Mantyasih inscription The Mantyasih inscription (also known as Balitung charter and Kedu inscription) is an important inscription found and kept by Li Djok Ban in Ngadireja Parakan Temanggung, then the inscription was brought by one of the princes of Surakarta to brought to Surakarta and is now stored in the Radyapustaka Museum, Central Java, Indonesia. It is dated to 907[1]: 108 [2] and was created by King Balitung from...

 

Infinite sequence of differential equations In mathematics, the KdV hierarchy is an infinite sequence of partial differential equations which contains the Korteweg–de Vries equation. Details Let T {\displaystyle T} be translation operator defined on real valued functions as T ( g ) ( x ) = g ( x + 1 ) {\displaystyle T(g)(x)=g(x+1)} . Let C {\displaystyle {\mathcal {C}}} be set of all analytic functions that satisfy T ( g ) ( x ) = g ( x ) {\displaystyle T(g)(x)=g(x)} , i.e. periodic functio...