程序员机器学习和人工智能入门

重新组织函数 - Substitute Algorithm

2017-11-06  本文已影响0人  scottlin

简述

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

动机

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

做法

上一篇 下一篇

猜你喜欢

热点阅读