TITLE: A Short Introduction to the Law of Demeter AUTHOR: Eugene Wallingford DATE: December 14, 2012 3:50 PM DESC: ----- BODY: Preface My students spent the last three weeks of the semester implementing some of the infrastructure for a Twitter-like messaging app. They grew the app in three iterations, with new and changed features at each step. In the readme file for one of the versions, a student commented:
I wound up having a lot of code of the sort
```  thisCollection.thisInsideCollection.thisAttribute.thisMethod()
```
I smiled and remembered again that even students who would never write such code in a smaller, more focused setting can be lulled into writing it in the process of growing a big, complicated program. I made a mental note to pay a little extra attention the next time I teach the course to the Law of Demeter. I actually don't talk much about the Law of Demeter in this sophomore-level course, because it's a name we don't need. But occasionally I'd like to point a student to a discussion of it, and there don't seem to be a lot of resources at the right level for these students. So I decided to draft the beginnings of a simple reference. I welcome your suggestions on how to make it better. You might also check out The Paperboy, The Wallet, and The Law Of Demeter, a nice tutorial I recently came across. What is the Law of Demeter? The Law of Demeter isn't a law so much as a general principle for software design. It is often referred to in the context of object-oriented programming, so you may see it phrased in terms of objects:
Objects should have short reach.
Or:
An object should not try to know too much, or need to.
The law's Wikipedia entry has a nice object-free formulation:
Only talk to your immediate friends.
If those are too squishy for you, the Wikipedia entry also as a more formal summary:
The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).
Framed this way, the Law of Demeter is just a restatement of OOP 101. Objects are independent. They encapsulate their state and behavior. Instance variables are private, and we should be suspicious of getter methods. As a matter of programming style, I often introduce this principle in a pragmatic way:
An operation should live with the data it uses.
Those are all general statements of the Law of Demeter. You will sometimes see a much more specific, formal statement of this sort:
A method m of an object obj may send messages only to these objects:
• obj itself
• obj's instance variables
• m's formal parameters
• any objects created within m
```  thisCollection.thisInsideCollection.thisAttribute.thisMethod()
```  thisCollection.doSomething()