Law of Demeter
(LOD) discourages long chain of calling. It says to call methods only on the objects directly composed within the class, or the objects created inside a method, objects passed as parameters in methods. If B b;
is a field in class A
and B
has a field of type C
, (C c;
) then inside A.java
, its not good practice to call b.c.performOperation();
.
As per my understanding we should have small methods in each class doing the operations on the field they has within them rather that outside world extracting the fields and calling the methods. Also I understand we can use Visitor pattern
to achieve this. But then I read Adapter is also one way to implement this, which I could not understand.
Adapter simply has the object of Adaptee
class in it and implements the interface
of another system (both Adaptee
and the interface
being in-compatible to each-other). It uses delegation to call method on Adaptee
. Here LOD
does not seam to be violated but I can not see if we would have not used Adapter pattern then how the law was being broken?
The reference I took from is from site : http://c2.com/cgi/wiki/LawOfDemeter?LawOfDemeter
ObjectQueries? and the AdapterPattern are two ways to implement the LawOfDemeter. -- DaveOrme