TDD(测试驱动开发)Dev练功房代码优雅

TDD和重构练习-FizzBuzz Sprint 3 - 集成测

2019-05-16  本文已影响5人  CodingDetails

FizzBuzz

Sprint 3

步骤分解

实现主程序

public class Main {
    public static void main(String[] args) {
        Game game = new Game(100);
        game.play();
    }
}
public class Game {
    private int count;

    public Game(int i) {
        this.count = i;
    }

    public void play() {
        for (int i = 0; i < this.count; i++) {
            FizzBuzz item = new FizzBuzz(i);
            System.out.println(item.toString());
        }
    }
}

重构

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Executable> rules = Rules.all();
        Game game = new Game(rules);
        game.play(100);
    }
}
import java.util.List;

public class Game {

    private final List<Executable> rules;

    public Game(List<Executable> rules) {
        this.rules = rules;
    }

    public void play(int count) {
        for (int i = 0; i < count; i++) {
            FizzBuzz item = new FizzBuzz(i);
            System.out.println(item.apply(this.rules));
        }
    }
}
public String apply(List<Executable> rules) {
    return rules.stream()
            .map(rule -> rule.exec(this.value))
            .filter(value -> !value.isEmpty())
            .distinct()
            .reduce(String::concat)
            .orElse(String.valueOf(this.value));
}
public class FizzBuzzTest {
    @ParameterizedTest(name = "should return {0} given {1}")
    @CsvSource({
            "1, 1",
            "3, Fizz",
            "5, Buzz",
            "15, FizzBuzz",
            "31, Fizz",
            "56, Buzz",
            "53, FizzBuzz",
    })
    void should_play_fizz_buzz(int input, String expected) {
        FizzBuzz item = new FizzBuzz(input);
        assertEquals(expected, item.apply(Rules.all()));
    }
}

后续变化

目前只实现了一个规则集合的创建方法Rules.all,后续需求变化时,可提供新的工厂方法来创建规则集合,由main方法传给Game类。

Over

上一篇下一篇

猜你喜欢

热点阅读