Brian Kernighan对编程风格的建议

sorra 发表于 2016 06/08 20:38 修改于 01/11 21:47 阅读数640
  • 简单直接地表达你的意图

  • 用"电话测试"来检查可读性 (想象在电话中向别人讲解这个程序)

  • 要清晰——不要过于聪明

  • 不要用条件分支来代替逻辑表达式

  • 用括号来避免歧义

  • 每当你做一次判断,做相应的操作

  • 每个判断之后要紧跟相应的操作(与上一句同义)

  • 使用语言好的特性,避免使用不好的特性

  • 捕捉控制流中的规律,以及数据中的反常/例外

  • 每个模块做好一件事 (FORTRAN的模块,可引申为现代语言的函数、对象)

  • 注释要与代码一致

  • 不要在注释中复述代码,注释要有意义

  • 不要注释掉烂代码——重写它

  • 用符号常量,不要直接把magic number写在代码里

  • 小心副作用和求值顺序

  • 宏不是函数 (宏没有独立作用域,而且容易出意外)

  • 小心off-by-one错误 (循环多了一次或少了一次)

  • 测试边界情况

  • 防御式编程

  • 确保输入别破坏程序的限制 (尤其是越界、缓冲区溢出)

  • 优化之前,先把它做对

  • 优化时,确保它仍是对的

  • 不要为效率而牺牲可读性

  • 持续改进,不要止步于第一版

附原文:

Brian Kernighan's Programming Style Tips

Here is a summary of the very important programming style tips from Brian Kernighan's 1994 guest CS50 lecture.

  • Say what you mean, simply and directly.

  • Use the ``telephone test'' for readability.

  • Write clearly - don't be too clever.

  • Don't use conditional expressions as a substitute for a logical expression.

  • Parenthesize to avoid ambiguity.

  • Each time you make a test, do something.

  • Follow each decision as closely as possible with its associated action.

  • Use the good features of a language; avoid the bad ones.

  • Capture regularity in control flow, irregularity in data.

  • Each module should do one thing well.

  • Make sure comments and code agree.

  • Don't just echo the code with comments - make every comment count.

  • Don't comment bad code - rewrite it.

  • Use symbolic constants for magic numbers.

  • Watch out for side effects and order of evaluation.

  • Macros are not functions.

  • Watch out for off-by-one errors.

  • Test programs at their boundaries.

  • Program defensively.

  • Make sure input cannot violate the limits of the program.

  • Make it right before you make it faster.

  • Keep it right when you make it faster.

  • Don't sacrifice clarity for small gains in ``efficiency.''

  • Don't stop with your first draft.

[From The Elements of Programming Style, Kernighan & Plauger, McGraw-Hill, 1978]