Designing an error case
The other day I stumbled upon a seven year old blog post by @dan_menges called Misunderstanding the Law of Demeter. It’s a great post, and it includes a nice code sample for the classic “paperboy” example of Demeter violation:
class Wallet
attr_accessor :cash
end
class Customer
has_one :wallet
end
class Paperboy
def collect_money(customer, due_amount)
if customer.wallet.cash < due_ammount
raise InsufficientFundsError
else
customer.wallet.cash -= due_amount
@collected_amount += due_amount
end
end
end
I love examples like this, and I like Dan’s improved design later in the post (go read that now). The reason I like this example is because it contains more meat, and therefore more context, than the standard “isn’t customer.getWallet().getCash(amount) terrible!” examples we often see (I’m as guilty of that as anyone). And in that extra context lies an interesting design question…
First though, I’m going to translate Dan’s code from Ruby into Java, so that we can see past some of the syntactic sugar to what’s really happening:
class Wallet {
public int cash;
}
class Customer {
public Wallet wallet;
}
class Paperboy {
private int collected_amount;
public void collect_money(Customer customer, int due_amount) {
if (customer.wallet.cash < due_amount)
throw new InsufficientFundsError();
customer.wallet.cash -= due_amount;
collected_amount += due_amount;
}
}
(This version isn’t identical to the Ruby, which has getter and setter methods for the cash field in the Wallet, but it’s close enough for our purposes.)
Anyway, back to the point. What interests me most about Dan’s code is the InsufficientFundsException. As soon as I saw that exception being thrown, I stopped to think about this code for a good few minutes. And so I have a question for you:
Would you throw that exception there?
If you would, why?
And if you wouldn’t, why not?
Feel free to answer in the comments here, or write your own post and link to it from the comments. I’ll post my thoughts in a few days.
Kevin Rutherford's Blog
- Kevin Rutherford's profile
- 20 followers

