代码重构
来源:互联网 发布:网络举报网站 编辑:程序博客网 时间:2024/06/05 03:20
面试落下好多节课,现在重新捡起来。 P.S. 到了HR面,好开心OVO 2015/04/23 14:41
首先是重构的概念:
重构(名词):对软件内部结构的一种调整,目的是在不改变软件可观察行为的前提下,提高其可理解性,降低其修改成本。Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior.重构(动词):使用一系列重构手法,在不改变软件可观察行为的前提下,调整其结构。Refactor (verb): to restructure software by applying a series of refactorings without changing its observable behavior..摘自<重构 改善既有代码的设计>
也就是说重构是为了使得程序变得容易理解。当然重构得建立在不影响程序正常运行结果
每当我要进行重构的时候,第一个步骤永远相同:我得为即将修改的代码建立一组可靠的测试环境.摘自<重构 改善既有代码的设计>
好的 现在开始将常见的重构情况(22种代码味道,这里的味道是smelly)整理成下表:
类内味道
类间味道
//提炼函数:public class Report { public static void report(Writer out, List machines, Robot robot) throws IOException) { out.write("FACTORY REPORT\n"); Iterator line = machine.iterator(); while (line.hasNext()) { Machine machine = (Machine)line.next(); out.write("Machine " + machine.name()); if (machine.bin() != null) out.write(" bin= " + machine.bin()); out.write("\n"); } out.write("\n"); out.write("Robot"); if (robot.location() != null) out.write(" location =" + robot.location().name()); if (robot.bin() != null) out.write(" bin = " + robot.bin()); out.write("\n");out.write ("==========\n"); } }//change to...public static void report (PrintStream out, List machines, Robot robot) { reportHeader(out); reportMachines(out, machines); reportRobot(out, robot); reportFooter(out);}//以上代码摘自weiliu_china上面将大片的代码提取成函数(这大片的代码实质上是移动到其他函数中),有何好处呢?1,增加代码的复用性相似的情况只需调用这些函数即可2,便于代码维护假设此时需要修改对Footer的report,只需修改reportFooter函数,而不是一改改多处(后面会提到霰弹式修改),便于维护其实,良好的代码风格就是:用人不疑。"放心"的调用里面的函数而不关心里面如何实现(因为如果干涉里面的实现,会在调用前(后)增加额外的代码,实质上是增加了自身的特殊性以及对这个函数的依赖性,如果这个函数里面的实现发生变化,有可能这边的代码也需要变化,这就是耦合。以后找到一个较好的例子再好好解释。)比较好的例子是OSI模型。OSI模型中 上下层之间是通过相应的接口通信的,上下层之间并不关心对方具体如何实现,他只知道对方提供的接口能实现他的功能所以当某一层内部发生修改的时候,他的上下层不需要修改(因为我知道他会帮我做好我交付给他的事,至于他的私生活,我觉得并不影响我对他的看法)感兴趣可以去看"迪米特法则"
//分解条件表达式:
//塑造模板方法:两个兄弟类之间含有相同的代码,父类构建一个模板,让兄弟类不同的实现作为填充剂。class A:public void getTea() { //... //warm the water by stove //clean the silver tea pot //put the green tea //...}class B:public void getTea() { //... //warm the water by stove //clean the silver tea pot //put the black tea //...}//change to:class Father:protected abstract void putTea();...public void getTea() { //... putTea(); //...}class A(B)分别实现独有的putTea()操作。
thanks to http://www.cnblogs.com/matchcolor/tag/%E9%87%8D%E6%9E%84/
0 0
- [ 重构 ] 代码重构!
- 关于代码重构
- 代码重构简介
- 代码重构简介
- 谈谈代码重构
- 代码重构简介
- 部分重构代码
- 代码重构
- 代码重构
- 谈谈代码重构
- 代码重构浅谈
- 代码重构
- 代码重构
- 如何重构代码
- 代码重构
- 谈谈代码重构
- 代码重构
- 代码重构清单
- 利用SIP将C++封装为Python
- LitePal vs GreenDAO vs SQLOpenHelper 性能比較
- Java第一天整理和第二天
- GDB 调试基本命令
- 并查集_HDU_1325
- 代码重构
- Android---28---Handler、Loop、MessageQueue的工作原理:
- zmalloc.h:50:31: 致命错误:jemalloc/jemalloc.h(redis)
- ORA-19808: recovery destination parameter mismatch
- android简单实现音乐播放器
- Elasticsearch之scroll
- 2015.4.20.21.03_数组_2014.4.20.21.03_ JAVA数组的定义及使用方法_0.03
- 黑马程序员——内部类
- CocoaPods安装和使用教程