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

动机
          使用此项重构手法之前,先要确定自己已经尽可能分解了源函数。替换一个巨大而复杂的算法很困难,只有先将它分解为较简单的小型函数,然后才可能很有把握的进行算法替换。
做法
.
实践
.




posted @ 2013-11-27 15:12  tanhaiyuan  阅读(183)  评论(0编辑  收藏  举报