重构 v.s. 重写 (refactor v.s. rebuild)
访问量: 4181
虽然重构这本书出现了14年,自己在重构方面也有一些实践(从07年开始),但是我发现重构在实际应用中还是需要思考一下的。 ( Although the book <<refactoring>> has been published for 14 years , and I had this kind of experience since 2007, I found that in the real world, we should think for a while before we do the refactoring. )
是重构合适,还是重写合适? ( should it be refactored , or rebuilt? )
我的意见是,如果代码的质量很差,就不值得为其重构。差代码的特点是: ( my suggestion is: let's rebuild it if it doesn't worth refactoring. The bad code looks like: )
1. 命名很糟糕。绕来绕去的。最怕怕的例子: red = 'green', success = 'false', get_an_apple() => 'banana' ( terrible naming)
2. 逻辑很糟糕。大段大段的复制代码。 ( terrible logic)
3. 底层架构就是错的。 ( totally incorrect infrastructure code )
在这样的差代码下做重构是浪费时间。一般说来,重构的步骤是: ( to refactor this kind of code kinda of wasting time. I would rather ask the business analyser for the re-build. generally, the steps for refactoring are: )
1. 保证代码可以运行 ( make sure the targe code is running )
2. 读懂代码,可以写单元测试或者 回归测试 ( read the code , know the logic, and write the unit tests)
3. 开始着手重构。 写代码 ,运行测试,写代码,运行测试。。。 (start refactoring, run tests, write code, run tests, write code ... )
我觉得让一个十年经验的程序员去读一个烂代码,从代码中分析业务逻辑,不如直接让他直接去找业务人员,了解业务需求。然后按照他自己的理解来重写。 ( It's not a good idea to make a ten-years experienced programmer to read the code written by a newbie with lots of terrible code with bad smells )
那么,在什么时候重构合适呢? 我觉得有三种情况: ( So, when should we do the refactoring? I think there are 3 cases: )
1. 这个代码没有时间重写了。 (no time to write a new project )
2. 这个代码正在生产环境中使用。没法在短时间内把它停下来。或者说,一换下来,就会发生重大的生产事故,没人敢碰。 ( this code is running for production purpose )
3. 两个人的水平相差的不太悬殊。而且底层代码的架构不是差得离谱。还有拯救的可能。( the previous coder's ability is not too bad, and the infrastructure is not so bad. )