I have a simple Store
class that contains an Inventory
. The Inventory
contains a list of Item
s. In order to modify one of the Item
s in the Inventory
, I'd have to write:
Store store( /*parameters*/ );
store.accessInventory(/*password*/).accessItem(/*item name*/).setPrice(9.50);
As I understand it, this breaks the Law of Demeter because Store
has to reach through Inventory
and into Item
in order to call setPrice()
.
I'd like to reconcile this violation of the law with the violation of the law in the classic example with the paper boy and the customer. In the paper boy example, the paper boy "knows" too much about the customer by assuming he will make his payment with a wallet. If the customer's method of payment changes, the paper boy will have to change as well.
What assumptions in my code are being made that could result in a problem like the one encountered in the paper boy example?
I understand that the Law is really more of a guideline, and that abiding by it in this case may not be the best idea, but I'd like to at least understand the Law before I move on. Thanks.
Your code is assuming that the Inventory object is the only object that will ever need to be notified when a price changes.
Imagine that in addition to containing an Inventory of items, your Store also had some advertising posters hung up in its windows.
If you followed the law of Demeter, your Store object might have a nice method like this:
... but if you instead allow the calling code to access the inventory object directly, then there is no easy/foolproof way to make sure that the advertisements always get updated whenever a price gets updated, so chances are that at some point your store's advertising posters will show an old/wrong price for a product. The Law of Demeter makes it easier to avoid that sort of bug.