Substitute Algorithm(替换算法)

  1. String foundPerson(String[] people){
  2. for (int i =0; i < people.length; i++){
  3. if (people[i].equals("Don")) {
  4. return "Don";
  5. }
  6. if (people[i].equals("John")) {
  7. return "John";
  8. }
  9. if (people[i].equals("Kent")) {
  10. return "Kent";
  11. }
  12. }
  13. return "";
  14. }

修改后:

String foundPerson(String[] people){
  List candidates = Arrays.asList(new String[]{"Don", "John", "Kent"});
  for (int i = 0; i < people.length; i++) {
    if (candidates.contains(people[i])){
      return people[i];
    }
  }
  return "";
}

做法

  • 准备好一个(替换用)算法,让它通过编译

  • 针对现有测试,执行上述的新算法。如果结果与原本结果相同,重构结束。

  • 如果测试结果不同于原先,在测试和调试过程中,以旧算法为比较参照标准。

    对于每个测试用例,分别以新旧两种算法执行,并观察两者结果是否相同。这可以帮助你看到哪一个测试用例出现麻烦,以及出现了怎样的麻烦