1

I got myself reading a article regarding changing the existing bad code into a good one. For reference, this is the link to the article http://www.javaworld.com/jw-03-2001/jw-0323-badcode.html?page=1

It broadly talked about the following

  • Add comments

  • Re-Factoring Code

    • Break large classes into smaller classes
    • Break large functions into smaller functions
    • Change code which is difficult to understand
  • Use Layered architecture

Seems good. Any addons to this list which you all may have come across ?

4

7 回答 7

9

Before doing any refactoring, ensure you have a suite of regression tests that you can run on the code. It's no good refactoring your code base if you then introduce thousands of regression bugs due to missing a slight nuance to what the original 'bad' code was actually doing (and missing it out in the refactoring).

于 2008-10-10T10:46:49.843 回答
3

Regarding comments, it's good practise to use JavaDocs. It's like building documentation as you code.

于 2008-10-10T10:47:55.457 回答
3

Martin Fowler wrote an excellent book on refactoring.

Here is the catalog of refactorings from the book.

于 2008-10-10T10:55:41.463 回答
1

确保您拥有一整套回归测试!

抓住 FindBugs、PMD 等,开始看看他们要说什么。我倾向于发现报告最多 Findbugs 错误的类有很多问题,并且是开始重构工作的好地方。

另一个值得一看的工具是 STAN4J,它会生成结构指标,向您展示代码设计真正可以改进的地方。它将检测脆弱的继承层次结构、糟糕的抽象等。这些肯定是任何重构工作的目标。

值得始终关注这些工具,如果您学会如何解释他们对您说的话,它们将极大地帮助您。

还要注意您的 IDE 的警告,它们的存在是有原因的。

  • 我不隶属于任何这些工具提供商(即使它们是免费的),但是我确实经常使用它们并且对它们印象深刻!
于 2008-10-13T02:38:28.303 回答
1

Read it and tinker with it, commenting as you go, so that you understand fully it before you permanently change any code.

于 2008-10-10T10:47:43.930 回答
1

Most code can be refactored from the high-level interface (and creating one of these could be a good start for any refactoring project).

It's not worth reimplementing from scratch, because the old code might have lots of special cases or workaround or non-documented but necessary behaviour. Therefore always use the existing code as a basis for refactoring.

Document as you learn the existing codebase by adding in JavaDocs and comments. This can form the basis of your redesign later on as you understand what the code does.

It can be that simply refactoring and changing variable names can aid readability a lot. Always look to do simpler refactorings if possible, especially if the code works and is just a little hard to maintain due to these simple issues.

于 2008-10-10T10:51:16.310 回答
0

问问自己为什么要重构代码。代码需要摸吗?通过改进它很容易破坏脆弱的代码。

如果您决定需要更改代码,那么正如其他人提到的那样,拥有一套测试将有很大帮助。

查看您正在修改的文件的修订历史记录,并查看是否已进行任何更改以修复错误,这样您就可以避免重新编写这些错误。

如果您出于性能原因重构代码,请留意算法改进。如果您可以在代码的热门部分将 O(n^2) 算法更改为 O(n log(n)) ,那么与其他任何数量的小更改相比,这可以为您的代码做更多的事情。

于 2008-10-13T21:20:02.003 回答