Learn to Code in 5 Minutes a Day: Lesson 9
By Code with ADHD
- 2 minutes read - 251 wordsLesson 8 Solution: Roman Numeral III
Yesterday’s exercise was to get to roman numeral III. Did you get something like this?
roman.go
func roman(number int) string {
if number == 3 {
return "III"
}
if number == 2 {
return "II"
}
return "I"
}
roman_test.go
package main
import (
"testing"
)
func TestRoman1(t *testing.T) {
result := roman(1)
expected := "I"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
func TestRoman2(t *testing.T) {
result := roman(2)
expected := "II"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
func TestRoman3(t *testing.T) {
result := roman(3)
expected := "III"
if result != expected {
t.Errorf("result was incorrect, got: %v, want: %v.", result, expected)
}
}
Were you able to get this or something similar? If not, go back and see if you can get 3/III working on your own.
Lesson 9: Cleaning Up (Refactoring)
Today we are going to cover a couple of new concepts.
- cleaning up (refactoring)
- for loop
So far we have just been hard coding in each number. Obviously this will work. But the goal of programming is to automate things and make them simpler. When we find ourselves programming things and it seems like there should be a cleaner/easier/better way to do things, we call this refactoring.
Times to refactor:
- when you repeat yourself
- when you notice you’re doing things differently for things that maybe should be the same.