
00:00:00
外卖卷:非常划算 扫码领劵 省点小钱钱
文章发布较早,内容可能过时,阅读注意甄别。
今天就不放洋屁了,来聊一下业界知名的书 《Refactoring_ Improving the Design of Existing Code 》 ,第一部发布于2011年,第二部在第一部发行的8年后。
个人阅读两本书之后发现第二部相比于第一部其实变化并不是特别大,唯一显著区别是第二部是用的JS而第一部使用JAVA,这是因为最近几年前后端涌现了各种新编程语言并且快速崛起,使用JS这种弱类型的并且语法规范相对宽松的语言可以有更多的受众,说白了就是让不仅仅局限于后端,让学前端的同学也能学到重构思想。
作为后端来说开发人员来说,推荐阅读是:第一部 > 第二部。
Refactoring 这是作者的个人博客网站。建议看下面的内容之前,先看看作者的博客介绍,也可以锻炼下英语阅读能力。
除开第一部中文版搜不到之外,其他都包含在里面:
链接:https://pan.baidu.com/s/18wqWbQbOTClrdaQwKwERDg?pwd=mg5t 提取码:mg5t --来自百度网盘超级会员V7的分享
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.
为什需要重构最好的话是Linux之父的“Show me the code”,不要逼逼那么多,代码写的好我就承认你很牛。
我建议把这段话反复多看几遍,也是个人认为的重构的核心思想。
Once I've done that change, I then add the new feature. Once I've added a feature and got it working, I often notice that the resulting code, while it works, isn't as clear as it could be. I then refactor it into a better shape so that when I (or someone else) return to this code in a few weeks time, I won't have to spend time puzzling out how this code works.
从这一段话意思出发,重构的核心是“改变”,如果重构之后没有对过去的“缺陷”进行修复,那么重构就是失败的,反之如果重构之后能让程序看起来更为简洁并且能跑的更快一点点,那都可以算是有效重构。
最后一句话我可以断定作者一定是一个懒鬼,实际上重构并不是浪费更多的时间在自己认为已经“完工”的代码折腾,相反,良好简洁易懂的代码不仅自己看着赏心悦目,下一个代码的接任者自己也会更舒服一些,看到设计良好的代码虽然有可能会觉得很抽象很痛苦百思不得其解,但是很能激发学习欲望。
根本原因:如果CRUD这种简单的事情都不能做到极致,如何去做更加复杂的事情?
I look at the existing code and consider whether it's structured in such a way to make the new change straightforward. If it isn't, then I refactor the existing code to make this new addition easy. By refactoring first in this way, I usually find it's faster than if I hadn't carried out the refactoring first.
很简单,你觉得难以理解,代码难以扩展的时候就应该立刻改进,作者在书中提到了“童子军”规则比较实用,每次进入一个类或者方法,都做一点点的改进,比如修复注释,修改变量名,养成良好的习惯是重构的基本功。
This code may be functions I can easily call, or hidden inside larger functions. If I struggle to understand this code, I refactor it so I won't have to struggle again next time I look at it. If there's some functionality buried in there that I need, I refactor so I can easily use it.
不是所有的代码都需要重构,要把时间花在值得优化的地方。另外看着不舒服的代码要尽快进行调整,不要在代码中埋雷。
(However new people regularly enter our profession and need to learn about refactoring. )This book helps them to learn, and for experienced developers to pass on their skills.
这里照应了我在引言中讨论的内容,因为软件行业的人群大批量涌入,作者对于重构的案例基本上是全盘重写了,语言也换了,包括作者的博客网站也都是JS的案例。
If you have the book you can access the web edition of the book, which is the canonical edition. It includes several refactorings not in the book, as well as an expanded example. In the future I intend to add more material to the web edition.
作者还在自己的博客里面藏了一手书中没有的案例,目的是提高自己的博客知名度 。
此外在博客中作者制作了有关自己重构(第二版)原则的快速导航,地址如下:
https://refactoring.com/catalog/
《代码简洁之道》也是一本老书,可以快速翻一下。我比较喜欢里面的一句:只有通过批评,我们才能学到东西。医生就是这样做的,飞行员就是这样做的,律师就是这样做的,我们程序员也需要学习如何这样做。(252页)
个人印象最深刻的是第一版中重构的程序,看着作者把屎山推倒并且代码变得容易扩展,这种感觉真的很棒。
评论