Law of Demeter.
Also called the Principle of Least Knowledge, the Law of Demeter enforces encapsulation by restricting what a method is allowed to talk to. It permits a method to send messages to four places:rL5
-
Its own class instance or
self
. -
self
‘s components or class/instance variables. - Objects in its arguments.
- Objects it instantiates.
In other words, a method is not allowed to access the methods on the return values of those messages. Dot-chaining is therefore not allowed, and subsequent work must be delegated to other methods. This encourages a class to expose methods that exactly represent what its clients want rather than delegating work to them. This leads to more generalized/reusable behaviors, but can also add verbosity in the form of wrapper methods.
-
↩
K.J. Lieberherr and I.M. Holland, “Assuring Good Style for Object-Oriented Programs,” IEEE Software 6, no. 5 (September 1989): 38–48, https://doi.org/10.1109/52.35588. (See notes.)