Is it allowed to call components' components according to the Law of Demeter?
By component I mean an object
which was "exclusively" injected into the container or was created in the container
which has the same life cycle with it's container
For example, Brain
is a component of a Dog
:
partial class Dog
{
private readonly IBrain brain;
public Dog(IBrain brain)
{
this.brain = brain;
}
}
Here is some information I found:
http://c2.com/cgi/wiki?LawOfDemeter
Your method can call methods on its own fields directly (but not on the fields' fields)
message target can only be one of the following objects:
... an object referred to by the object's attribute
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
A method of an object should invoke only the methods of the following kinds of objects:
...
any objects it creates/instantiates
its direct component objects
And here is a case:
partial class Dog
{
public void Command(string cmd)
{
var movement = brain.GetMemory().GetMovement(cmd);
skeleton.ExecuteMovement(movement);
}
}
Is it allowed to call components' components according to the Law of Demeter?
By definition this is not allowed since you should Only talk to your immediate friends.
In other words, the IBrain
service should not expose its internal services through its interface (assuming that GetMemory()
returns an IMemory
service of some kind). Instead, the IBrain
interface should either provide provide a method that allows retrieving the movement -or- the IMemory should be injected directly into
Dog`.