Refactor (一) :Refactor As A Routine Work
What refactor ?
Refactoring is done to fill in short-cuts, eliminate duplication and dead code, and to make the design and logic clear.Always to simplify the code and to make it easier to understand. Always to make it easier and safer to change in the future.
Why refactor ?
- 代码写得脏
可读性差、逻辑不清,导致问题不断,阻碍快速迭代开发。
迫于“时间紧迫、需求易变、编码能力”,那时那刻“思路不清晰”地写出“不堪入目”代码。
- 框架单薄,无力支持
随着业务量增加,现有的架构太单薄,无力支持庞大的业务量,不得不“Large Scale Refactoring”。
How refactor ?
- Confirm your understanding of code
首先弄懂代码、增加必要注释。针对业务复杂的,借助UML梳理业务
- Make refactor safe
Regression test your refactoring work and Reviewing all of these changes , ensure that you haven’t changed the behavior – it still works the same.
- Make refactor simple
Refactoring patterns and refactoring tools in modern IDEs make refactoring easy, safe and cheap. Refactoring can and should be folded in to how you write and maintain code – a part of the everyday discipline of development, like writing tests and reviewing code. It should be done quietly, continuously and implicitly. It becomes part of the cost of doing work, folded in to estimates and risk assessments. Done properly, it doesn’t need to be explained or justified.
题外话
写代码 似于 写字
写得“赏心悦目”:那是个人水平问题。水平不济只能勤加练习。
写得“清楚明白”:那是个人态度问题。是一笔一画,还是草草了事。写代码 有别于 写字
写字:”一笔下去,重不临摹” ;写代码:”反复推敲”。
因为写代码,需要一定逻辑思维活动。这就是为什么,有些写得条理清晰,有些写得一团乱麻。建议事先在草稿纸上写伪代码,然后再实现编码,对于Geek而言:不必“过分设计”、编写详细文档。
个人愚见:“字写得不错的人,写出的代码都不会太差”。
总之,起码要写得让人明白;要写出水平,还待后天勤奋(多看源码、多敲键盘)。
下列场景,建议不去编码 “过于劳累时不去编码;和家人在一起时不去编码”。
附 录
catalog of refactorings Martin Fowler
clean code Robert Cecil Martin
Don’t Live with Broken Windows Bill Venners