Roman Numerals

You can find all the code for this chapter here

Some companies will ask you to do the Roman Numeral Kata as part of the interview process. This chapter will show how you can tackle it with TDD.

We are going to write a function which converts an Arabic number (numbers 0 to 9) to a Roman Numeral.

If you haven’t heard of Roman Numerals they are how the Romans wrote down numbers.

You build them by sticking symbols together and those symbols represent numbers

So I is “one”. III is three.

Seems easy but there’s a few interesting rules. V means five, but IV is 4 (not IIII).

MCMLXXXIV is 1984. That looks complicated and it’s hard to imagine how we can write code to figure this out right from the start.

As this book stresses, a key skill for software developers is to try and identify “thin vertical slices” of useful functionality and then iterating. The TDD workflow helps facilitate iterative development.

So rather than 1984, let’s start with 1.

Write the test first

  1. func TestRomanNumerals(t *testing.T) {
  2. got := ConvertToRoman(1)
  3. want := "I"
  4. if got != want {
  5. t.Errorf("got %q, want %q", got, want)
  6. }
  7. }

If you’ve got this far in the book this is hopefully feeling very boring and routine to you. That’s a good thing.

Try to run the test

./numeral_test.go:6:9: undefined: ConvertToRoman

Let the compiler guide the way

Write the minimal amount of code for the test to run and check the failing test output

Create our function but don’t make the test pass yet, always make sure the tests fails how you expect

  1. func ConvertToRoman(arabic int) string {
  2. return ""
  3. }

It should run now

  1. === RUN TestRomanNumerals
  2. --- FAIL: TestRomanNumerals (0.00s)
  3. numeral_test.go:10: got '', want 'I'
  4. FAIL

Write enough code to make it pass

  1. func ConvertToRoman(arabic int) string {
  2. return "I"
  3. }

Refactor

Not much to refactor yet.

I know it feels weird just to hard-code the result but with TDD we want to stay out of “red” for as long as possible. It may feel like we haven’t accomplished much but we’ve defined our API and got a test capturing one of our rules; even if the “real” code is pretty dumb.

Now use that uneasy feeling to write a new test to force us to write slightly less dumb code.

Write the test first

We can use subtests to nicely group our tests

  1. func TestRomanNumerals(t *testing.T) {
  2. t.Run("1 gets converted to I", func(t *testing.T) {
  3. got := ConvertToRoman(1)
  4. want := "I"
  5. if got != want {
  6. t.Errorf("got %q, want %q", got, want)
  7. }
  8. })
  9. t.Run("2 gets converted to II", func(t *testing.T) {
  10. got := ConvertToRoman(2)
  11. want := "II"
  12. if got != want {
  13. t.Errorf("got %q, want %q", got, want)
  14. }
  15. })
  16. }

Try to run the test

  1. === RUN TestRomanNumerals/2_gets_converted_to_II
  2. --- FAIL: TestRomanNumerals/2_gets_converted_to_II (0.00s)
  3. numeral_test.go:20: got 'I', want 'II'

Not much surprise there

Write enough code to make it pass

  1. func ConvertToRoman(arabic int) string {
  2. if arabic == 2 {
  3. return "II"
  4. }
  5. return "I"
  6. }

Yup, it still feels like we’re not actually tackling the problem. So we need to write more tests to drive us forward.

Refactor

We have some repetition in our tests. When you’re testing something which feels like it’s a matter of “given input X, we expect Y” you should probably use table based tests.

  1. func TestRomanNumerals(t *testing.T) {
  2. cases := []struct {
  3. Description string
  4. Arabic int
  5. Want string
  6. }{
  7. {"1 gets converted to I", 1, "I"},
  8. {"2 gets converted to II", 2, "II"},
  9. }
  10. for _, test := range cases {
  11. t.Run(test.Description, func(t *testing.T) {
  12. got := ConvertToRoman(test.Arabic)
  13. if got != test.Want {
  14. t.Errorf("got %q, want %q", got, test.Want)
  15. }
  16. })
  17. }
  18. }

We can now easily add more cases without having to write any more test boilerplate.

Let’s push on and go for 3

Write the test first

Add the following to our cases

  1. {"3 gets converted to III", 3, "III"},

Try to run the test

  1. === RUN TestRomanNumerals/3_gets_converted_to_III
  2. --- FAIL: TestRomanNumerals/3_gets_converted_to_III (0.00s)
  3. numeral_test.go:20: got 'I', want 'III'

Write enough code to make it pass

  1. func ConvertToRoman(arabic int) string {
  2. if arabic == 3 {
  3. return "III"
  4. }
  5. if arabic == 2 {
  6. return "II"
  7. }
  8. return "I"
  9. }

Refactor

OK so I’m starting to not enjoy these if statements and if you look at the code hard enough you can see that we’re building a string of I based on the size of arabic.

We “know” that for more complicated numbers we will be doing some kind of arithmetic and string concatenation.

Let’s try a refactor with these thoughts in mind, it might not be suitable for the end solution but that’s OK. We can always throw our code away and start afresh with the tests we have to guide us.

  1. func ConvertToRoman(arabic int) string {
  2. var result strings.Builder
  3. for i:=0; i<arabic; i++ {
  4. result.WriteString("I")
  5. }
  6. return result.String()
  7. }

You may not have used strings.Builder before

A Builder is used to efficiently build a string using Write methods. It minimizes memory copying.

Normally I wouldn’t bother with such optimisations until I have an actual performance problem but the amount of code is not much larger than a “manual” appending on a string so we may as well use the faster approach.

The code looks better to me and describes the domain as we know it right now.

The Romans were into DRY too…

Things start getting more complicated now. The Romans in their wisdom thought repeating characters would become hard to read and count. So a rule with Roman Numerals is you cant have the same character repeated more than 3 times in a row.

Instead you take the next highest symbol and then “subtract” by putting a symbol to the left of it. Not all symbols can be used as subtractors; only I (1), X (10) and C (100).

For example 5 in Roman Numerals is V. To create 4 you do not do IIII, instead you do IV.

Write the test first

  1. {"4 gets converted to IV (cant repeat more than 3 times)", 4, "IV"},

Try to run the test

  1. === RUN TestRomanNumerals/4_gets_converted_to_IV_(cant_repeat_more_than_3_times)
  2. --- FAIL: TestRomanNumerals/4_gets_converted_to_IV_(cant_repeat_more_than_3_times) (0.00s)
  3. numeral_test.go:24: got 'IIII', want 'IV'

Write enough code to make it pass

  1. func ConvertToRoman(arabic int) string {
  2. if arabic == 4 {
  3. return "IV"
  4. }
  5. var result strings.Builder
  6. for i:=0; i<arabic; i++ {
  7. result.WriteString("I")
  8. }
  9. return result.String()
  10. }

Refactor

I dont “like” that we have broken our string building pattern and I want to carry on with it.

  1. func ConvertToRoman(arabic int) string {
  2. var result strings.Builder
  3. for i := arabic; i > 0; i-- {
  4. if i == 4 {
  5. result.WriteString("IV")
  6. break
  7. }
  8. result.WriteString("I")
  9. }
  10. return result.String()
  11. }

In order for 4 to “fit” with my current thinking I now count down from the Arabic number, adding symbols to our string as we progress. Not sure if this will work in the long run but let’s see!

Let’s make 5 work

Write the test first

  1. {"5 gets converted to V", 5, "V"},

Try to run the test

  1. === RUN TestRomanNumerals/5_gets_converted_to_V
  2. --- FAIL: TestRomanNumerals/5_gets_converted_to_V (0.00s)
  3. numeral_test.go:25: got 'IIV', want 'V'

Write enough code to make it pass

Just copy the approach we did for 4

  1. func ConvertToRoman(arabic int) string {
  2. var result strings.Builder
  3. for i := arabic; i > 0; i-- {
  4. if i == 5 {
  5. result.WriteString("V")
  6. break
  7. }
  8. if i == 4 {
  9. result.WriteString("IV")
  10. break
  11. }
  12. result.WriteString("I")
  13. }
  14. return result.String()
  15. }

Refactor

Repetition in loops like this are usually a sign of an abstraction waiting to be called out. Short-circuiting loops can be an effective tool for reabability but it could also be telling you something else.

We are looping over our Arabic number and if we hit certain symbols we are calling break but what we are really doing is subtracting over i in a ham-fisted manner.

  1. func ConvertToRoman(arabic int) string {
  2. var result strings.Builder
  3. for arabic > 0 {
  4. switch {
  5. case arabic > 4:
  6. result.WriteString("V")
  7. arabic -= 5
  8. case arabic > 3:
  9. result.WriteString("IV")
  10. arabic -= 4
  11. default:
  12. result.WriteString("I")
  13. arabic--
  14. }
  15. }
  16. return result.String()
  17. }
  • Given the signals I’m reading from our code, driven from our tests of some very basic scenarios I can see that to build a Roman Numeral I need to subtract from arabic as I apply symbols
  • The for loop no longer relies on an i and instead we will keep building our string until we have subtracted enough symbols away from arabic.

I’m pretty sure this approach will be valid for 6 (VI), 7 (VII) and 8 (VIII) too. Nonetheless add the cases in to our test suite and check (I wont include the code for brevity, check the github for samples if you’re unsure).

9 follows the same rule as 4 in that we should subtract I from the representation of the following number. 10 is represented in Roman Numerals with X; so therefore 9 should be IX.

Write the test first

  1. {"9 gets converted to IX", 9, "IX"}

Try to run the test

  1. === RUN TestRomanNumerals/9_gets_converted_to_IX
  2. --- FAIL: TestRomanNumerals/9_gets_converted_to_IX (0.00s)
  3. numeral_test.go:29: got 'VIV', want 'IX'

Write enough code to make it pass

We should be able to adopt the same approach as before

  1. case arabic > 8:
  2. result.WriteString("IX")
  3. arabic -= 9

Refactor

It feels like the code is still telling us there’s a refactor somewhere but it’s not totally obvious to me, so let’s keep going.

I’ll skip the code for this too, but add to your test cases a test for 10 which should be X and make it pass before reading on.

Here are a few tests I added as I’m confident up to 39 our code should work

  1. {"10 gets converted to X", 10, "X"},
  2. {"14 gets converted to XIV", 14, "XIV"},
  3. {"18 gets converted to XVIII", 18, "XVIII"},
  4. {"20 gets converted to XX", 20, "XX"},
  5. {"39 gets converted to XXXIX", 39, "XXXIX"},

If you’ve ever done OO programming, you’ll know that you should view switch statements with a bit of suspicion. Usually you are capturing a concept or data inside some imperative code when in fact it could be captured in a class structure instead.

Go isn’t strictly OO but that doesn’t mean we ignore the lessons OO offers entirely (as much as some would like to tell you).

Our switch statement is describing some truths about Roman Numerals along with behaviour.

We can refactor this by decoupling the data from the behaviour.

  1. type RomanNumeral struct {
  2. Value int
  3. Symbol string
  4. }
  5. var RomanNumerals = []RomanNumeral {
  6. {10, "X"},
  7. {9, "IX"},
  8. {5, "V"},
  9. {4, "IV"},
  10. {1, "I"},
  11. }
  12. func ConvertToRoman(arabic int) string {
  13. var result strings.Builder
  14. for _, numeral := range RomanNumerals {
  15. for arabic >= numeral.Value {
  16. result.WriteString(numeral.Symbol)
  17. arabic -= numeral.Value
  18. }
  19. }
  20. return result.String()
  21. }

This feels much better. We’ve declared some rules around the numerals as data rather than hidden in an algorithm and we can see how we just work through the Arabic number, trying to add symbols to our result if they fit.

Does this abstraction work for bigger numbers? Extend the test suite so it works for the Roman number for 50 which is L.

Here are some test cases, try and make them pass.

  1. {"40 gets converted to XL", 40, "XL"},
  2. {"47 gets converted to XLVII", 47, "XLVII"},
  3. {"49 gets converted to XLIX", 49, "XLIX"},
  4. {"50 gets converted to L", 50, "L"},

If you’re a cheater, all you needed to add to the RomanNumerals array is

  1. {50, "L"},
  2. {40, "XL"},

And the rest!

Here are the remaining symbols

Arabic Roman
100 C
500 D
1000 M

Take the same approach for the remaining symbols, it should just be a matter of adding data to both the tests and our array of symbols.

Does your code work for 1984: MCMLXXXIV ?

Here is my final test suite

  1. func TestRomanNumerals(t *testing.T) {
  2. cases := []struct {
  3. Arabic int
  4. Roman string
  5. }{
  6. {Arabic: 1, Roman: "I"},
  7. {Arabic: 2, Roman: "II"},
  8. {Arabic: 3, Roman: "III"},
  9. {Arabic: 4, Roman: "IV"},
  10. {Arabic: 5, Roman: "V"},
  11. {Arabic: 6, Roman: "VI"},
  12. {Arabic: 7, Roman: "VII"},
  13. {Arabic: 8, Roman: "VIII"},
  14. {Arabic: 9, Roman: "IX"},
  15. {Arabic: 10, Roman: "X"},
  16. {Arabic: 14, Roman: "XIV"},
  17. {Arabic: 18, Roman: "XVIII"},
  18. {Arabic: 20, Roman: "XX"},
  19. {Arabic: 39, Roman: "XXXIX"},
  20. {Arabic: 40, Roman: "XL"},
  21. {Arabic: 47, Roman: "XLVII"},
  22. {Arabic: 49, Roman: "XLIX"},
  23. {Arabic: 50, Roman: "L"},
  24. {Arabic: 100, Roman: "C"},
  25. {Arabic: 90, Roman: "XC"},
  26. {Arabic: 400, Roman: "CD"},
  27. {Arabic: 500, Roman: "D"},
  28. {Arabic: 900, Roman: "CM"},
  29. {Arabic: 1000, Roman: "M"},
  30. {Arabic: 1984, Roman: "MCMLXXXIV"},
  31. {Arabic: 3999, Roman: "MMMCMXCIX"},
  32. {Arabic: 2014, Roman: "MMXIV"},
  33. {Arabic: 1006, Roman: "MVI"},
  34. {Arabic: 798, Roman: "DCCXCVIII"},
  35. }
  36. for _, test := range cases {
  37. t.Run(fmt.Sprintf("%d gets converted to %q", test.Arabic, test.Roman), func(t *testing.T) {
  38. got := ConvertToRoman(test.Arabic)
  39. if got != test.Roman {
  40. t.Errorf("got %q, want %q", got, test.Roman)
  41. }
  42. })
  43. }
  44. }
  • I removed description as I felt the data described enough of the information.
  • I added a few other edge cases I found just to give me a little more confidence. With table based tests this is very cheap to do.

I didn’t change the algorithm, all I had to do was update the RomanNumerals array.

  1. var RomanNumerals = []RomanNumeral{
  2. {1000, "M"},
  3. {900, "CM"},
  4. {500, "D"},
  5. {400, "CD"},
  6. {100, "C"},
  7. {90, "XC"},
  8. {50, "L"},
  9. {40, "XL"},
  10. {10, "X"},
  11. {9, "IX"},
  12. {5, "V"},
  13. {4, "IV"},
  14. {1, "I"},
  15. }

Parsing Roman Numerals

We’re not done yet. Next we’re going to write a function that converts from a Roman Numeral to an int

Write the test first

We can re-use our test cases here with a little refactoring

Move the cases variable outside of the test as a package variable in a var block.

  1. func TestConvertingToArabic(t *testing.T) {
  2. for _, test := range cases[:1] {
  3. t.Run(fmt.Sprintf("%q gets converted to %d", test.Roman, test.Arabic), func(t *testing.T) {
  4. got := ConvertToArabic(test.Roman)
  5. if got != test.Arabic {
  6. t.Errorf("got %d, want %d", got, test.Arabic)
  7. }
  8. })
  9. }
  10. }

Notice I am using the slice functionality to just run one of the tests for now (cases[:1]) as trying to make all of those tests pass all at once is too big a leap

Try to run the test

  1. ./numeral_test.go:60:11: undefined: ConvertToArabic

Write the minimal amount of code for the test to run and check the failing test output

Add our new function definition

  1. func ConvertToArabic(roman string) int {
  2. return 0
  3. }

The test should now run and fail

  1. --- FAIL: TestConvertingToArabic (0.00s)
  2. --- FAIL: TestConvertingToArabic/'I'_gets_converted_to_1 (0.00s)
  3. numeral_test.go:62: got 0, want 1

Write enough code to make it pass

You know what to do

  1. func ConvertToArabic(roman string) int {
  2. return 1
  3. }

Next, change the slice index in our test to move to the next test case (e.g. cases[:2]). Make it pass yourself with the dumbest code you can think of, continue writing dumb code (best book ever right?) for the third case too. Here’s my dumb code.

  1. func ConvertToArabic(roman string) int {
  2. if roman == "III" {
  3. return 3
  4. }
  5. if roman == "II" {
  6. return 2
  7. }
  8. return 1
  9. }

Through the dumbness of real code that works we can start to see a pattern like before. We need to iterate through the input and build something, in this case a total.

  1. func ConvertToArabic(roman string) int {
  2. total := 0
  3. for range roman {
  4. total++
  5. }
  6. return total
  7. }

Write the test first

Next we move to cases[:4] (IV) which now fails because it gets 2 back as that’s the length of the string.

Write enough code to make it pass

  1. // earlier..
  2. type RomanNumerals []RomanNumeral
  3. func (r RomanNumerals) ValueOf(symbol string) int {
  4. for _, s := range r {
  5. if s.Symbol == symbol {
  6. return s.Value
  7. }
  8. }
  9. return 0
  10. }
  11. // later..
  12. func ConvertToArabic(roman string) int {
  13. total := 0
  14. for i := 0; i < len(roman); i++ {
  15. symbol := roman[i]
  16. // look ahead to next symbol if we can and, the current symbol is base 10 (only valid subtractors)
  17. if i+1 < len(roman) && symbol == 'I' {
  18. nextSymbol := roman[i+1]
  19. // build the two character string
  20. potentialNumber := string([]byte{symbol, nextSymbol})
  21. // get the value of the two character string
  22. value := romanNumerals.ValueOf(potentialNumber)
  23. if value != 0 {
  24. total += value
  25. i++ // move past this character too for the next loop
  26. } else {
  27. total++
  28. }
  29. } else {
  30. total++
  31. }
  32. }
  33. return total
  34. }

This is horrible but it does work. It’s so bad I felt the need to add comments.

  • I wanted to be able to look up an integer value for a given roman numeral so I made a type from our array of RomanNumerals and then added a method to it, ValueOf
  • Next in our loop we need to look ahead if the string is big enough and the current symbol is a valid subtractor. At the moment it’s just I (1) but can also be X (10) or C (100).
    • If it satisfies both of these conditions we need to lookup the value and add it to the total if it is one of the special subtractors, otherwise ignore it
    • Then we need to further increment i so we dont count this symbol twice

Refactor

I’m not entirely convinced this will be the long-term approach and there’s potentially some interesting refactors we could do, but I’ll resist that in case our approach is totally wrong. I’d rather make a few more tests pass first and see. For the meantime I made the first if statement slightly less horrible.

  1. func ConvertToArabic(roman string) int {
  2. total := 0
  3. for i := 0; i < len(roman); i++ {
  4. symbol := roman[i]
  5. if couldBeSubtractive(i, symbol, roman) {
  6. nextSymbol := roman[i+1]
  7. // build the two character string
  8. potentialNumber := string([]byte{symbol, nextSymbol})
  9. // get the value of the two character string
  10. value := romanNumerals.ValueOf(potentialNumber)
  11. if value != 0 {
  12. total += value
  13. i++ // move past this character too for the next loop
  14. } else {
  15. total++
  16. }
  17. } else {
  18. total++
  19. }
  20. }
  21. return total
  22. }
  23. func couldBeSubtractive(index int, currentSymbol uint8, roman string) bool {
  24. return index+1 < len(roman) && currentSymbol == 'I'
  25. }

Write the test first

Let’s move on to cases[:5]

  1. === RUN TestConvertingToArabic/'V'_gets_converted_to_5
  2. --- FAIL: TestConvertingToArabic/'V'_gets_converted_to_5 (0.00s)
  3. numeral_test.go:62: got 1, want 5

Write enough code to make it pass

Apart from when it is subtractive our code assumes that every character is a I which is why the value is 1. We should be able to re-use our ValueOf method to fix this.

  1. func ConvertToArabic(roman string) int {
  2. total := 0
  3. for i := 0; i < len(roman); i++ {
  4. symbol := roman[i]
  5. // look ahead to next symbol if we can and, the current symbol is base 10 (only valid subtractors)
  6. if couldBeSubtractive(i, symbol, roman) {
  7. nextSymbol := roman[i+1]
  8. // build the two character string
  9. potentialNumber := string([]byte{symbol, nextSymbol})
  10. if value := romanNumerals.ValueOf(potentialNumber); value != 0 {
  11. total += value
  12. i++ // move past this character too for the next loop
  13. } else {
  14. total++ // this is fishy...
  15. }
  16. } else {
  17. total+=romanNumerals.ValueOf(string([]byte{symbol}))
  18. }
  19. }
  20. return total
  21. }

Refactor

When you index strings in Go, you get a byte. This is why when we build up the string again we have to do stuff like string([]byte{symbol}). It’s repeated a couple of times, let’s just move that functionality so that ValueOf takes some bytes instead.

  1. func (r RomanNumerals) ValueOf(symbols ...byte) int {
  2. symbol := string(symbols)
  3. for _, s := range r {
  4. if s.Symbol == symbol {
  5. return s.Value
  6. }
  7. }
  8. return 0
  9. }

Then we can just pass in the bytes as is, to our function

  1. func ConvertToArabic(roman string) int {
  2. total := 0
  3. for i := 0; i < len(roman); i++ {
  4. symbol := roman[i]
  5. if couldBeSubtractive(i, symbol, roman) {
  6. if value := romanNumerals.ValueOf(symbol, roman[i+1]); value != 0 {
  7. total += value
  8. i++ // move past this character too for the next loop
  9. } else {
  10. total++ // this is fishy...
  11. }
  12. } else {
  13. total+=romanNumerals.ValueOf(symbol)
  14. }
  15. }
  16. return total
  17. }

It’s still pretty nasty, but it’s getting there.

If you start moving our cases[:xx] number through you’ll see that quite a few are passing now. Remove the slice operator entirely and see which ones fail, here’s some examples from my suite

  1. === RUN TestConvertingToArabic/'XL'_gets_converted_to_40
  2. --- FAIL: TestConvertingToArabic/'XL'_gets_converted_to_40 (0.00s)
  3. numeral_test.go:62: got 60, want 40
  4. === RUN TestConvertingToArabic/'XLVII'_gets_converted_to_47
  5. --- FAIL: TestConvertingToArabic/'XLVII'_gets_converted_to_47 (0.00s)
  6. numeral_test.go:62: got 67, want 47
  7. === RUN TestConvertingToArabic/'XLIX'_gets_converted_to_49
  8. --- FAIL: TestConvertingToArabic/'XLIX'_gets_converted_to_49 (0.00s)
  9. numeral_test.go:62: got 69, want 49

I think all we’re missing is an update to couldBeSubtractive so that it accounts for the other kinds of subtractive symbols

  1. func couldBeSubtractive(index int, currentSymbol uint8, roman string) bool {
  2. isSubtractiveSymbol := currentSymbol == 'I' || currentSymbol == 'X' || currentSymbol =='C'
  3. return index+1 < len(roman) && isSubtractiveSymbol
  4. }

Try again, they still fail. However we left a comment earlier…

  1. total++ // this is fishy...

We should never be just increment total as that implies every symbol is a I. Replace it with

  1. total += romanNumerals.ValueOf(symbol)

And all the tests pass! Now that we have fully working software we can indulge ourselves in some refactoring, with confidence

Refactor

Here is all the code I finished up with. I had a few failed attempts but as I keep emphasising, that’s fine and the tests help me play around with the code freely.

  1. import "strings"
  2. func ConvertToArabic(roman string) (total int) {
  3. for _, symbols := range windowedRoman(roman).Symbols() {
  4. total += allRomanNumerals.ValueOf(symbols...)
  5. }
  6. return
  7. }
  8. func ConvertToRoman(arabic int) string {
  9. var result strings.Builder
  10. for _, numeral := range allRomanNumerals {
  11. for arabic >= numeral.Value {
  12. result.WriteString(numeral.Symbol)
  13. arabic -= numeral.Value
  14. }
  15. }
  16. return result.String()
  17. }
  18. type romanNumeral struct {
  19. Value int
  20. Symbol string
  21. }
  22. type romanNumerals []romanNumeral
  23. func (r romanNumerals) ValueOf(symbols ...byte) int {
  24. symbol := string(symbols)
  25. for _, s := range r {
  26. if s.Symbol == symbol {
  27. return s.Value
  28. }
  29. }
  30. return 0
  31. }
  32. func (r romanNumerals) Exists(symbols ...byte) bool {
  33. symbol := string(symbols)
  34. for _, s := range r {
  35. if s.Symbol == symbol {
  36. return true
  37. }
  38. }
  39. return false
  40. }
  41. var allRomanNumerals = romanNumerals{
  42. {1000, "M"},
  43. {900, "CM"},
  44. {500, "D"},
  45. {400, "CD"},
  46. {100, "C"},
  47. {90, "XC"},
  48. {50, "L"},
  49. {40, "XL"},
  50. {10, "X"},
  51. {9, "IX"},
  52. {5, "V"},
  53. {4, "IV"},
  54. {1, "I"},
  55. }
  56. type windowedRoman string
  57. func (w windowedRoman) Symbols() (symbols [][]byte) {
  58. for i := 0; i < len(w); i++ {
  59. symbol := w[i]
  60. notAtEnd := i+1 < len(w)
  61. if notAtEnd && isSubtractive(symbol) && allRomanNumerals.Exists(symbol, w[i+1]) {
  62. symbols = append(symbols, []byte{byte(symbol), byte(w[i+1])})
  63. i++
  64. } else {
  65. symbols = append(symbols, []byte{byte(symbol)})
  66. }
  67. }
  68. return
  69. }
  70. func isSubtractive(symbol uint8) bool {
  71. return symbol == 'I' || symbol == 'X' || symbol == 'C'
  72. }

My main problem with the previous code is similar to our refactor from earlier. We had too many concerns coupled together. We wrote an algorithm which was trying to extract Roman Numerals from a string and then find their values.

So I created a new type windowedRoman which took care of extracting the numerals, offering a Symbols method to retrieve them as a slice. This meant our ConvertToArabic function could simply iterate over the symbols and total them.

I broke the code down a bit by extracting some functions, especially around the wonky if statement to figure out if the symbol we are currently dealing with is a two character subtractive symbol.

There’s probably a more elegant way but I’m not going to sweat it. The code is there and it works and it is tested. If I (or anyone else) finds a better way they can safely change it - the hard work is done.

An intro to property based tests

There have been a few rules in the domain of Roman Numerals that we have worked with in this chapter

  • Cant have more than 3 consecutive symbols
  • Only I (1), X (10) and C (100) can be “subtractors”
  • Taking the result of ConvertToRoman(N) and passing it to ConvertToArabic should return us N

The tests we have written so far can be described as “example” based tests where we provide the tooling some examples around our code to verify.

What if we could take these rules that we know about our domain and somehow exercise them against our code?

Property based tests help you do this by throwing random data at your code and verifying the rules you describe always hold true. A lot of people think property based tests are mainly about random data but they would be mistaken. The real challenge about property based tests is having a good understanding of your domain so you can write these properties.

Enough words, let’s see some code

  1. func TestPropertiesOfConversion(t *testing.T) {
  2. assertion := func(arabic int) bool {
  3. roman := ConvertToRoman(arabic)
  4. fromRoman := ConvertToArabic(roman)
  5. return fromRoman == arabic
  6. }
  7. if err := quick.Check(assertion, nil); err != nil {
  8. t.Error("failed checks", err)
  9. }
  10. }

Rationale of property

Our first test will check that if we transform a number into Roman, when we use our other function to convert it back to a number that we get what we originally had.

  • Given random number (e.g 4).
  • Call ConvertToRoman with random number (should return IV if 4).
  • Take the result of above and pass it to ConvertToArabic.
  • The above should give us our original input (4).

This feels like a good test to build us confidence because it should break if there’s a bug in either. The only way it could pass is if they have the same kind of bug; which isn’t impossible but feels unlikely.

Technical explanation

We’re using the testing/quick package from the standard library

Reading from the bottom, we provide quick.Check a function that it will run against a number of random inputs, if the function returns false it will be seen as failing the check.

Our assertion function above takes a random number and runs our functions to test the property.

Run our test

Try running it; your computer may hang for a while, so kill it when you’re bored :)

What’s going on? Try adding the following to the assertion code.

  1. assertion := func(arabic int) bool {
  2. if arabic <0 || arabic > 3999 {
  3. log.Println(arabic)
  4. return true
  5. }
  6. roman := ConvertToRoman(arabic)
  7. fromRoman := ConvertToArabic(roman)
  8. return fromRoman == arabic
  9. }

You should see something like this:

  1. === RUN TestPropertiesOfConversion
  2. 2019/07/09 14:41:27 6849766357708982977
  3. 2019/07/09 14:41:27 -7028152357875163913
  4. 2019/07/09 14:41:27 -6752532134903680693
  5. 2019/07/09 14:41:27 4051793897228170080
  6. 2019/07/09 14:41:27 -1111868396280600429
  7. 2019/07/09 14:41:27 8851967058300421387
  8. 2019/07/09 14:41:27 562755830018219185

Just running this very simple property has exposed a flaw in our implementation. We used int as our input but:

  • You cant do negative numbers with Roman Numerals
  • Given our rule of a max of 3 consecutive symbols we cant represent a value greater than 3999 (well, kinda) and int has a much higher maximum value than 3999.

This is great! We’ve been forced to think more deeply about our domain which is a real strength of property based tests.

Clearly int is not a great type. What if we tried something a little more appropriate?

uint16

Go has types for unsigned integers, which means they cannot be negative; so that rules out one class of bug in our code immediately. By adding 16, it means it is a 16 bit integer which can store a max of 65535, which is still too big but gets us closer to what we need.

Try updating the code to use uint16 rather than int. I updated assertion in the test to give a bit more visibility.

  1. assertion := func(arabic uint16) bool {
  2. if arabic > 3999 {
  3. return true
  4. }
  5. t.Log("testing", arabic)
  6. roman := ConvertToRoman(arabic)
  7. fromRoman := ConvertToArabic(roman)
  8. return fromRoman == arabic
  9. }

If you run the test they now actually run and you can see what is being tested. You can run multiple times to see our code stands up well to the various values! This gives me a lot of confidence that our code is working how we want.

The default number of runs quick.Check performs is 100 but you can change that with a config.

  1. if err := quick.Check(assertion, &quick.Config{
  2. MaxCount:1000,
  3. }); err != nil {
  4. t.Error("failed checks", err)
  5. }

Further work

  • Can you write property tests that check the other properties we described?
  • Can you think of a way of making it so it’s impossible for someone to call our code with a number greater than 3999?
    • You could return an error
    • Or create a new type that cannot represent > 3999
      • What do you think is best?

Wrapping up

More TDD practice with iterative development

Did the thought of writing code that converts 1984 into MCMLXXXIV feel intimidating to you at first? It did to me and I’ve been writing software for quite a long time.

The trick, as always, is to get started with something simple and take small steps.

At no point in this process did we make any large leaps, do any huge refactorings, or get in a mess.

I can hear someone cynically saying “this is just a kata”. I cant argue with that, but I still take this same approach for every project I work on. I never ship a big distributed system in my first step, I find the simplest thing the team could ship (usually a “Hello world” website) and then iterate on small bits of functionality in manageable chunks, just like how we did here.

The skill is knowing how to split work up, and that comes with practice and with some lovely TDD to help you on your way.

Property based tests

  • Built into the standard library
  • If you can think of ways to describe your domain rules in code, they are an excellent tool for giving you more confidence
  • Force you to think about your domain deeply
  • Potentially a nice complement to your test suite

Postscript

This book is reliant on valuable feedback from the community.Dave is an enormous help in practically everychapter. But he had a real rant about my use of ‘Arabic numerals’ in thischapter so, in the interests of full disclosure, here’s what he said.

Just going to write up why a value of type int isn’t really an ‘arabicnumeral’. This might be me being way too precise so I’ll completely understandif you tell me to f off.

A digit is a character used in the representation of numbers - from the Latinfor ‘finger’, as we usually have ten of them. In the Arabic (also calledHindu-Arabic) number system there are ten of them. These Arabic digits are:

  1. 0 1 2 3 4 5 6 7 8 9

A numeral is the representation of a number using a collection of digits.An Arabic numeral is a number represented by Arabic digits in a base 10positional number system. We say ‘positional’ because each digit hasa different value based upon its position in the numeral. So

  1. 1337

The 1 has a value of one thousand because its the first digit in a fourdigit numeral.

Roman are built using a reduced number of digits (I, V etc…) mainly asvalues to produce the numeral. There’s a bit of positional stuff but it’smostly I always representing ‘one’.

So, given this, is int an ‘Arabic number’? The idea of a number is not atall tied to its representation - we can see this if we ask ourselves what thecorrect representation of this number is:

  1. 255
  2. 11111111
  3. two-hundred and fifty-five
  4. FF
  5. 377

Yes, this is a trick question. They’re all correct. They’re the representationof the same number in the decimal, binary, English, hexadecimal and octalnumber systems respectively.

The representation of a number as a numeral is independent of its propertiesas a number - and we can see this when we look at integer literals in Go:

  1. 0xFF == 255 // true

And how we can print integers in a format string:

  1. n := 255
  2. fmt.Printf("%b %c %d %o %q %x %X %U", n, n, n, n, n, n, n, n)
  3. // 11111111 ÿ 255 377 'ÿ' ff FF U+00FF

We can write the same integer both as a hexadecimal and an Arabic (decimal)numeral.

So when the function signature looks like ConvertToRoman(arabic int) stringit’s making a bit of an assumption about how it’s being called. Becausesometimes arabic will be written as a decimal integer literal

  1. ConvertToRoman(255)

But it could just as well be written

  1. ConvertToRoman(0xFF)

Really, we’re not ‘converting’ from an Arabic numeral at all, we’re ‘printing’ -representing - an int as a Roman numeral - and ints are not numerals,Arabic or otherwise; they’re just numbers. The ConvertToRoman function ismore like strconv.Itoa in that it’s turning an int into a string.

But every other version of the kata doesn’t care about this distinction so:shrug: