Law of Demeter (Paper boy example)

David Bock has written a paper (David Bock Explains Law of Demeter) about the Law of Demeter using a paper boy example.

The first point is that the customer ususally does not give the wallet to the paper boy to pay for the paper bill. Instead, the customer takes out the money from the wallet and hands it to the paper boy.

Instead of using (in class PaperBoy)

// customer.wallet.totalMoney;
we use a method:
customer.getPayment(..)

The example is implemented in Java code using the DJ library with additional features added and some errors in the paper corrected.

An additional feature is that the customer might not have enough money in the wallet but the missing dollar bills might be in the kitchen cabinet or in the bedroom under the mattress. The program uses a traversal to find the money in the apartment. Following the Law of Demeter means not letting the paper boy into the bedroom or kitchen.

Instead of using (in class PaperBoy)

// customer.wallet.totalMoney;
// customer.apartment.bedroom.mattress.totalMoney;
// customer.apartment.kitchen.kitchenCabinet.totalMoney;
we use a complex request:
customer.getPayment(..)
The complex request is implemented using the traversal:
from Customer to TotalMoney

The example makes good use of the asList and gather methods of DJ. The complex request getPayment(..) uses traversal.asList(this) to collect the TotalMoney-objects that are subsequently updated by taking the payment out. traversal.gather(this) is used to check the money available before and after the transaction.

Back to Demeter home page

Professor Karl Lieberherr
College of Computer and Information Science Science, Northeastern University
Boston, MA 02115
lieber at ccs.neu.edu