How to reading code

曾经专门买过一本《代码阅读方法与实践》,"If you make a habit of reading good code, you will write better code yourself.”,可惜没有看几页。晚上偶尔看到几篇关于阅读代码的文章,摘要如下:

我为何爱读代码?你为何也应当爱?》,最早是从这篇文章开始的。如何阅读代码:

  1. 尝试亲自构建和运行程序。Try to build and run it.
  2. 别死盯细节。Don’t focus on the details just yet.
  3. 确保理解所有构造。Make sure you understand all the constructs.
  4. 待熟悉了大多数构造之后,就可以搞几次随机的深入探查了。Now that you’ve got a good idea about most of the constructs, it is time to do a couple of random deep-dives.
  5. 前几步中肯定还有你不明白的地方,现在最合适的就是跑几个测试,看看已有测试。There were undoubtedly things in the previous step you were confused about, so this is the perfect time to go and read some tests.
  6. 如果没有测试程序,这时候就该写上几个。No tests you say, sounds like the perfect time to write some.
  7. 把弄不懂的部分拿到单独的程序中来。Extract curious bits of code into standalone programs.
  8. 代码很乱很糟糕?那么重构吧。The code is dirty and smelly? Why not refactor it.
  9. 如果上面说的不管用,就找个同伴跟你一起读代码。If nothing seems to help, get yourself a code reading buddy.

Tips For Reading Code

  1. Build and run the program.
  2. Find the high-level logic.
  3. Draw some flowcharts.
  4. Examine library calls.
  5. Search for key words.
  6. Leverage the power of code comprehension tools.
  7. Print the code.
  8. Write UnitTests.
  9. Comment the code.
  10. Clean up the code.

Reading Code is Like Reading the Talmud

  1. Work in pairs, thinking out loud to one another.
  2. Argue.
  3. Skipping over the fragment of text has you stumped and seeing if you can come back to it later.
  4. Read the text both “inside” and “outside”.

posted on 2011-01-29 23:31  zhaorui  阅读(218)  评论(1编辑  收藏  举报

导航