Learn to Code In 5 Minutes A Day: Lesson 10
By Code with ADHD
- 2 minutes read - 355 wordsLesson 9 Solution: Refactoring
Yesterday’s exercise was to see if you could figure out a way to refactor our code so far. In other words, we wanted to see if we could simplify this code:
func roman(number int) string {
if number == 3 {
return "III"
}
if number == 2 {
return "II"
}
return "I"
}
The way we do this is with a loop. A loop lets us repeat things over and over and is one of the fundamental tools of programming. If you didn’t figure out how to simplify this on your own, please pause and see if searching for “golang for loop” helps you figure this out.
…
So assuming you did this and tried on your own, did you come up with something that looked like this?
func roman(number int) string {
result := ""
for i := 0; i < number; i++ {
result += "I"
}
return result
}
When you run your unit tests, you should see all your tests passing.
% go test
PASS
ok hello 0.175s
This is how you know you did it right. Are you starting to see the benefit of unit testing? It keeps you safe when you make changes so you can be sure you didn’t break anything.
Lesson 10: Moving Forward
If you don’t understand that “for” loop, you might want to start back at the beginning. This is foundational stuff, key to being able to make more progress.
The next logic step is, let’s add the number… 4.
Let’s write a test for 4… (can you do this on your own? The more you try on your own the better..)
func TestRoman4(t *testing.T) {
result := roman(4)
expected := "IV"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
Again, if you run your test, it should fail:
go test
--- FAIL: TestRoman4 (0.00s)
roman_test.go:32: result was incorrect, got: IIII, want: IV.
FAIL
exit status 1
FAIL hello 0.401s
Can you figure out how to add some code in romans.go to make this test pass? That’s the challenge for today.