Reputation: 5326
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
Upvotes: 1
Views: 198
Reputation: 33885
This is what I think they mean:
When they talk about using the adapter pattern to conform to Demeter's law, they are talking about another case than the standard adapter pattern use case you described.
Let's say we have a class, that someone else wrote, that exposes a public field:
public class DataClass {
public Data data;
}
When we want to access the data field anywhere in our code, we get call chains:
dataClass.data.doOperation()
An adapter can be used to 'hide' this call chain:
public class DataClassAdapter {
DataClass wrappedInstance;
public void doOperation() {
wrappedInstance.data.doOperation();
}
}
Then we can call like:
dataAdapter.doOperation();
Without the call chain.
I would argue that the word "Adapter" is somewhat misused here. Although the adapter pattern is somewhat similar.
Upvotes: 1