天天看點

修改代碼的藝術 讀書筆記(二,修改現有代碼的四種技巧)

在沒有Unit Tests的代碼下如何更好的更改代碼?四種方法:

1 Sprout Method,衍生方法

Class Experiment {

  void existingMethod() {

    ...

    sproutMethod();

    ...

  }

  void sproutMethod() {}

}

2 Sprout Class,衍生類

Class SproutClass {

  public static void experiment(){}

}

Class Experiment {

  void existingMethod() {

    SproutClass.experiment();

  }

}

3 Wrap Method,包裝方法

Class Experiment {

  void existingMethod(){

    System.out.println("existing method");

  }

  void wrapMethod() {

    // do additional things

    existingMehtod();

  }

}

Then make 'existingMethod' private and rename 'wrapMethod' to 'existingMethod'.

4 Wrap Class,包裝類

class WrapClass {

  Experiment experiment;

  public WrapClass(Experiment experiment);

  public existingMethod() {

    // do additional things

    experiment.existingMethod();

  }

}

用這四種方法是因為在現實世界中,每個任務都被配置設定一定的資源(時間,人力等),我們想使我們新寫的代碼有Unit Tests來保證品質,但是沒有更多的時間去增加沒有Unit Tests的已有的代碼的Unit Tests。條件是資源有限,追求的目标是使新寫的代碼有Unit Tests來保證品質。

原文這樣說:

When you introduce more interfaces and packages into your design to break dependencies, the amount of time it takes to rebuild the entire system goes up slightly. There are more files to

compile. But the average time for a make, a build based on what needs to be recompiled, can go down dramatically.

原文:http://blog.csdn.net/hongchangfirst/article/details/52150855

作者:hongchangfirst

hongchangfirst的首頁:http://blog.csdn.net/hongchangfirst