重构:改善既有代码的设计 第2版
Refactoring: Improving the Design of Existing Code, Second Edition
Chapter 1: 重构 第一个示例
如果要给一个程序添加一个特性, 但代码因为缺乏良好的结构而不易进行更改 – 先重构这个程序,让特性添加更为容易, 然后再添加新特性
测试先行
重构第一步: 一组可靠的测试集
把想达成的目标代码和测试里面各写一遍
重构后立即运行测试
提炼函数
: 将一块代码抽取成一个函数
永远将函数的返回值命名为“result”
用查询取代临时变量
临时变量影响函数抽象
内联变量
// const play = playFor(perf);
let thisAmount = amountFor(perf, playFor(perf));
拆分循环
一个循环只做一件事
滑动声明
把声明放到要使用的地方附近
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.