Chapter 2. Multicurrency Money

Followed fast and followed faster

Edgar Allen Poe, The Raven

Did the red-green-refactor cycle we followed in Chapter 1 seem a tad too slow?

A response of “Heck yes!” (or some rhyming phrase) is understandable!

The goal of test-driven development isn’t to force us to go slow—or fast, for that matter. Its goal is to allow us to go at a pace we’re comfortable with: speeding up when we can, slowing down when we should.

In this chapter, we’ll introduce additional currencies and the ability to multiply and divide money in any currency. Let’s see if we can kick up the pace a bit.

Enter the Euro

The second item on our list of features introduces a new currency:

5 USD × 2 = 10 USD

10 EUR × 2 = 20 EUR

4002 KRW / 4 = 1000.5 KRW

5 USD + 10 EUR = 17 USD

1 USD + 1100 KRW = 2200 KRW

This indicates that we need a more general entity than the Dollar we created in the previous chapter: something like Money, which encapsulates an amount (which we already have) and a currency (which we do not yet have). Let’s write tests to flesh out this new feature.


Let’s write a new test in money_test.go. This test requires that when a struct representing “10 EUR” is multiplied by 2, we get “20 EUR”:

func TestMultiplicationInEuros(t *testing.T) {
    tenEuros := Money{amount: 10, currency: "EUR"}
    twentyEuros := tenEuros.Times(2)
    if twentyEuros.amount != 20 {
        t.Errorf("Expected 20, got: [%d]", twentyEuros.amount)
    if twentyEuros.currency != "EUR" {
        t.Errorf("Expected ...

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.