2일 차: 수학이 없을 것이라고 들었습니다(보너스).

안녕하세요 스포츠 팬 여러분!

우리는 문제를 해결하는 동안 이전에 언급한 매우 작은 리팩터링을 살펴보기 위해 오늘 돌아왔습니다.

이 리팩토링을 하는 이유는 코드의 중복을 줄이기 위함입니다. 테스트 기반 개발 덕분에 멋지고 쉬운 프로세스가 될 것입니다.

복제된 코드를 살펴보겠습니다.

예 1:

func CalculatePresentArea(str string) int {
    s := strings.Split(str, "x")

    var sides []int
    for _, sideString := range s {
        side, _ := strconv.Atoi(sideString)
        sides = append(sides, side)
    }

    sort.Ints(sides)

    return sides[0]*sides[1]*3 + sides[0]*sides[2]*2 + sides[1]*sides[2]*2
}


예 2:

func CalculateRibbonLength(str string) int {
    s := strings.Split(str, "x")

    var sides []int
    for _, sideString := range s {
        side, _ := strconv.Atoi(sideString)
        sides = append(sides, side)
    }

    sort.Ints(sides)

    return sides[0] + sides[0] + sides[1] + sides[1] + sides[0]*sides[1]*sides[2]
}


보시다시피 이 두 함수의 대부분은 정확히 동일합니다.

따라서 이 프로세스를 DRY로 만드는 데 사용할 수 있는 함수에 대한 테스트를 작성해 보겠습니다.

func TestMakeSortedIntSlice(t *testing.T) {
    assert.Equal(t, []int{5, 13, 19}, MakeSortedIntSlice([]string{"13x5x19"}))
    assert.Equal(t, []int{22, 26, 28}, MakeSortedIntSlice([]string{"22x28x26"}))
    assert.Equal(t, []int{12, 26, 29}, MakeSortedIntSlice([]string{"29x26x12"}))
    assert.Equal(t, []int{4, 7, 17}, MakeSortedIntSlice([]string{"4x7x17"}))
    assert.Equal(t, []int{14, 30, 30}, MakeSortedIntSlice([]string{"30x30x14"}))
}


따라서 이 시점에서 go test를 실행하면 다음 오류가 발생합니다.

# github.com/damiensedgwick/aoc2015/day_2 [github.com/damiensedgwick/aoc2015/day_2.test]
./main_test.go:28:36: undefined: MakeSortedIntSlice
./main_test.go:29:37: undefined: MakeSortedIntSlice
./main_test.go:30:37: undefined: MakeSortedIntSlice
./main_test.go:31:35: undefined: MakeSortedIntSlice
./main_test.go:32:37: undefined: MakeSortedIntSlice
FAIL    github.com/damiensedgwick/aoc2015/day_2 [build failed]


이제 함수를 작성하고 이 테스트를 통과하도록 합시다.

func MakeSortedIntSlice(str string) []int {
    s := strings.Split(str, "x")

    var sides []int
    for _, sideString := range s {
        side, _ := strconv.Atoi(sideString)
        sides = append(sides, side)
    }

    sort.Ints(sides)

    return sides
}


테스트를 다시 실행하면 이제 테스트가 완벽하게 통과하고 있음을 알 수 있습니다.

이제 앞의 두 예제에서 복제된 코드를 다음과 같이 바꿀 수 있습니다.

예 1:

func CalculatePresentArea(str string) int {
    s := MakeSortedIntSlice(str)

    return s[0]*s[1]*3 + s[0]*s[2]*2 + s[1]*s[2]*2
}


예 2:

func CalculateRibbonLength(str string) int {
    s := MakeSortedIntSlice(str)

    return s[0] + s[0] + s[1] + s[1] + s[0]*s[1]*s[2]
}


훨씬 깨끗합니다!

이것은 다소 간단한 예였지만 테스트를 사용하여 코드를 리팩터링하는 것을 적극 권장합니다!

다음에는 3일차에 대해 알아보도록 하겠습니다. 그때 뵙겠습니다.

좋은 웹페이지 즐겨찾기