Money Example from Kent Beck's TDD by example

Lunivore already answered the question with how to solve the problem, but I think you should re-read the paragraph just before and after the block of code (and test), if you want to understand more on what Beck was trying to convey.

The last sentence reads "Here is the code we would have to modify to make it work:". That block of code was first entered on page 75 (with test case). Nothing was changed in end effect on page 79. It was just an indication of what we could change, if we wanted to keep this test.

"There is no obvious, clean way to check the currency of the argument if and only if it is Money. The experiment fails, we delete the test, and away we go".

He also stated that this test is ugly and concluded on the following page "Tried a brief experiment, then discarded it when it didn't work out".

I wrote this just in case you were thinking all of the examples just work and should be kept.


You're checking that the sum variable is a Money, but returning a Sum in the plus method.

So, unless Sum is a subclass of Money, that assertion will always fail.

To make it pass, you might want to do something like:

public Expression plus(Expression addend) {
    return new Money(...<whatever>...);
}

Of course, Money would then have to be an Expression too.

Or you might want to evaluate the sum to get the money out of it. Or maybe even do sum instanceof Sum instead. It depends on what behavior you're actually trying to achieve.

By the way, beware the instanceof operator.