Law of Demeter

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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 at Northeastern University towards the end of 1987, and can be succinctly summarized in one of the following ways:[1]

  • 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 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.

In object-oriented programming[edit]

When applied to object-oriented programs, the Law of Demeter can be more precisely called the “Law of Demeter for Functions/Methods” (LoD-F). In this case, 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 O may only invoke the methods of the following kinds of objects:[2]

  1. O itself
  2. m's parameters
  3. Any objects created/instantiated within m
  4. O's direct component objects
  5. A global variable, accessible by O, in the scope of m

In particular, an object should avoid invoking methods of a member 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". That is, the code a.b.Method() breaks the law where a.Method() 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[edit]

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 containers can be changed without reworking their callers.

Basili et al.[3] 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 (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; see Disadvantages.

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[edit]

Although the LoD increases the adaptiveness of a software system, it may also result in having to write many wrapper methods to propagate calls to components; in some cases, this can add noticeable time and space overhead.[3][4][5]

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.[6] On the other hand, at the class level, the LoD leads to wide (i.e. enlarged) interfaces, because the LoD requires introducing many auxiliary methods instead of digging directly into the object structures. One solution to the problem of enlarged class interfaces is the aspect-oriented approach,[7] where the behavior of the method is specified as an aspect at a high level of abstraction. This is done by having an adaptive method that encapsulates the behaviour of an operation into a place, with which the scattering problem is solved. It also abstracts over the class structure that results in avoiding the tangling problem. 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.[4][7]

Since the LoD exemplifies a specific type of coupling, and does not specify a method of addressing this type of coupling, it is more suited as a metric for code smell as opposed to a methodology for building loosely coupled systems.

See also[edit]

References[edit]

  1. ^ Macedo, Emerson. "README.markdown: Demeter". GitHub. Retrieved 2012-07-05. 
  2. ^ Bock, David. "The Paperboy, The Wallet, and The Law Of Demeter". College of Computer and Information Science, Northeastern University. p. 5. Retrieved 2012-07-05. 
  3. ^ a b Basili, Victor; Briand, L.; Melo, W. L. (October 1996). "A Validation of Object-Oriented Design Metrics as Quality Indicators". IEEE Transactions on Software Engineering 22 (10): 751–761. doi:10.1109/32.544352. "As expected, the larger the WMC, the larger the probability of fault detection." 
  4. ^ 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)." 
  5. ^ "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." 
  6. ^ Lieberherr, K.; Riel, A. (1988-09-25). "Object-Oriented Programming: An Objective Sense of Style". OOPSLA '88 Proceedings. Archived from the original on 1988-09-25. 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." 
  7. ^ a b Lieberherr, Karl; Orleans, Doug; Ovlinger, Johan (October 2001). "ASPECT-ORIENTED PROGRAMMING WITH ADAPTIVE METHODS". COMMUNICATIONS OF THE ACM. pp. 39–40. Retrieved 2012-07-05. "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[edit]

  • Lieberherr, Karl; Holland, I. (September 1989). "Assuring good style for object-oriented programs". IEEE Software: 38–48. 
  • Lieberherr, Karl J. (1995). "Adaptive Object-Oriented Software: The Demeter Method with Propagation Patterns". Boston: PWS Publishing Company, International Thomson Publishing. 
  • Hunt, Andrew; Thomas, David (2002). The Pragmatic Programmer: From Journeyman to Master. Addison-Wesley. pp. 140–141. 
  • Larman, Craig (2005). Applying UML and Patterns (3rd ed.). Prentice Hall. pp. 430–432.  (from this book, "Law of Demeter" is also known as "Don't talk to strangers")
  • McConnell, Steve (2004). Code Complete (2nd ed.). Microsoft Press. p. 150. 
  • Palermo, Jeffrey; Scheirman, Ben; Bogard, Jimmy (2009). ASP.NET MVC in Action. Manning Publications. p. 14. 

External links[edit]