美文网首页程序员机器学习和人工智能入门
重新组织函数 - Substitute Algorithm

重新组织函数 - Substitute Algorithm

作者: scottlin | 来源:发表于2017-11-06 22:16 被阅读0次

简述

Substitute Algorithm(替换算法)指你想把一个算法替换成另一个更清晰的算法,将函数本体替换为另一个算法。

String foundPerson(String[] people){
  for (int i = 0; i<people.length; i++){
    if (people[i].equals("Don")){
      return "Don";
    }
    if (people[i].equals("John")){
      return "John";
    }
    if (people[i].equals("Kent")){
      return "Kent";
     }
  }
return "";
}

改为

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 "";
}

动机

重构可以把一些复杂东西分解为较简单的小块,但有时你就必须壮士断腕,删除整个算法,代之以较简单的算法。而且解决这类问题往往有好几种方法。

做法

  • 准备好另一个(替换用)算法,让它通过编译
  • 针对现有测试,执行上诉的新算法。如果结果与原本结果相同,重构结束。
  • 如果测试结果不同于原先,在测试和调试过程中,以旧算法为比较参照标准。

相关文章

网友评论

    本文标题:重新组织函数 - Substitute Algorithm

    本文链接:https://www.haomeiwen.com/subject/diyrmxtx.html