Chapter 3. Portfolio

Penny wise and dollar foolish.1

Tired proverb

We can multiply and divide amounts in any one currency by numbers. Now we need to add amounts in multiple currencies.

5 USD x 2 = 10 USD

10 EUR x 2 = 20 EUR

4002 KRW / 4 = 1000.5 KRW

5 USD + 10 EUR = 17 USD

1 USD + 1100 KRW = 2200 KRW

Remove redundant Money multiplication tests

In this chapter, we’ll deal with the mixed-mode addition of currencies.

Designing Our Next Test

To test-drive the next feature—5 USD + 10 EUR = 17 USD—it’s enlightening to first sketch out how our program will evolve. TDD plays nicely with software design, contrary to prevailing myths!

The feature, as described in our feature list, says that 5 dollars and 10 euros should add up to 17 dollars, assuming we get 1.2 dollars for exchanging one euro.

However, it’s equally true that:

1 EUR + 1 EUR = 2.4 USD

Or, rather obviously:

1 EUR + 1 EUR = 2 EUR

An epiphany! When we add two (or more) Money entities, the result can be expressed in any currency, as long as we know the exchange rate between all currencies involved (i.e., from the currency of each Money into the currency in which we want to express the result). This is true even if all the currencies involved are the same—as in the last example, which is just one particular case out of many.

Tip

Test-driven development gives us an opportunity to pause after each RGR cycle and design our code intentionally.

We realize that “adding dollars to dollars results in dollars” is an ...

Get Learning Test-Driven Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.