曾经专门买过一本《代码阅读方法与实践》,"If you make a habit of reading good code, you will write better code yourself.”,可惜没有看几页。晚上偶尔看到几篇关于阅读代码的文章,摘要如下:
《我为何爱读代码?你为何也应当爱?》,最早是从这篇文章开始的。如何阅读代码:
- 尝试亲自构建和运行程序。Try to build and run it.
- 别死盯细节。Don’t focus on the details just yet.
- 确保理解所有构造。Make sure you understand all the constructs.
- 待熟悉了大多数构造之后,就可以搞几次随机的深入探查了。Now that you’ve got a good idea about most of the constructs, it is time to do a couple of random deep-dives.
- 前几步中肯定还有你不明白的地方,现在最合适的就是跑几个测试,看看已有测试。There were undoubtedly things in the previous step you were confused about, so this is the perfect time to go and read some tests.
- 如果没有测试程序,这时候就该写上几个。No tests you say, sounds like the perfect time to write some.
- 把弄不懂的部分拿到单独的程序中来。Extract curious bits of code into standalone programs.
- 代码很乱很糟糕?那么重构吧。The code is dirty and smelly? Why not refactor it.
- 如果上面说的不管用,就找个同伴跟你一起读代码。If nothing seems to help, get yourself a code reading buddy.
- Build and run the program.
- Find the high-level logic.
- Draw some flowcharts.
- Examine library calls.
- Search for key words.
- Leverage the power of code comprehension tools.
- Print the code.
- Write UnitTests.
- Comment the code.
- Clean up the code.
Reading Code is Like Reading the Talmud
- Work in pairs, thinking out loud to one another.
- Argue.
- Skipping over the fragment of text has you stumped and seeing if you can come back to it later.
- Read the text both “inside” and “outside”.