Skip to content

代码规范

代码可读性

https://github.com/CyC2018/CS-Notes

只有在核心领域为了效率才可以放弃可读性,否则可读性是第一位。

单词可替代单词
senddeliver、dispatch、announce、distribute、route
findsearch、extract、locate、recover
startlaunch、create、begin、open
makecreate、set up、build、generate、compose、add、new

布尔相关的命名加上 is、can、should、has 等前缀。

  • 用 min、max 表示数量范围;
  • 用 first、last 表示访问空间的包含范围;
  • begin、end 表示访问空间的排除范围,即 end 不包含尾部。
202304210541423

排列整齐的注释:

cpp
int a = 1;   // 注释
int b = 11;  // 注释
int c = 111; // 注释

不能因为有注释就随便起个名字,而是争取起个好名字而不写注释。

标记用法
TODO待做
FIXME待修复
HACK粗糙的解决方案
XXX危险!这里有重要的问题

编写注释要简洁明了,可以添加测试用例:

cpp
// Student's name -> Student's score
Map<String, Integer> scoreMap = new HashMap<>();

// ...
// Example: add(1, 2), return 3
int add(int x, int y) {
    return x + y;
}

控制流的可读性:左侧是变量,右侧是常数。

只有在逻辑简单的情况下使用 ? : 三目运算符来使代码更紧凑,否则应该拆分成 if / else;

do / while 的条件放在后面,不够简单明了,并且会有一些迷惑的地方,最好使用 while 来代替。

避免使用 goto。

长表达式的可读性很差,可以引入一些解释变量从而拆分表达式:

cpp
username = line.split(':')[0].strip()
if username == "root":
    ...

Released under the MIT License.