The Law of Demeter: “Use only one dot”, or “an object should avoid invoking methods of a member object returned by another method.”
But when would this not be a violation? Buried within a C2.com wiki page is this excellent exchange:
Trying to come up with a more simple (non-foobar) example, is this correct?
currentPerson.Account.Deposit(500) <– bad
Account.Deposit(currentPerson, 500) <– good
currentPerson.give(500) <– best
LawOfDemeter implies you shouldn’t care how currentPerson stores his money
In a banking system you would give money to someone’s account not to them, so far from being bad, navigating via the account object would convey essential semantics for example in the case the person had multiple accounts. If you have a canonical domain model then the all object relationships convey essential semantics about the information that is being represented. If you bridge those relationships before presenting access to client code then that information is lost. The fact that you could afford to bridge it implies that the structural information wasn’t needed and hence your model wasn’t canonical. If your model is non-canonical then refactor it so it is – don’t bridge it. Of course your client code will then be dependent on the structure of your model but that is essential in order for the it add value to the system. Hence so long as your model is canonical with respect to the problem domain then LawOfDemeter is an anachronism.
— Paul Campbell