<The Art of Readable Code> 笔记一

第1章  代码应易理解 (Code should be easy to understand)

基本原则:好的代码,能够减少 “别人” 理解它的时间。 “别人” 不仅指的是 “其它人”,也可能是 “以后的自己”

 

1  合习惯

Node* node = list->head;
if (node == NULL) return;

while(node->next != NULL) {
    Print(node->data)
    node = node->next;
}
if(node != NULL) Print(node->data);

  上面代码,等效于下面代码,但是很明显,后者更容易理解。

for (Node* node = list->head; node != NULL; node = node->next)
    Print(node->data);

2  少 ≠ 好

1)  少而好

// if 语句
if(exponent >= 0) {
    return mantissa * (1 << exponent);
} else {
    return mantissa / (1 << -exponent);
}

// 条件运算符
return exponent >= 0 ? mantissa * (1 << exponent) : mantissa / (1 << -exponent);

2)  少而不好

// 不易理解
assert ((!(bucket = FindBucket(key))) || !bucket->IsOccupied());

// 易理解
bucket = FindBucket(key);
if(bucket != NULL) asset(!bucket->IsOccupied());

3  加注释

// Fast version of "hash = (65599 * hash) + c"
hash = (hash << 6) + (hash << 16) -hash + c;
原文地址:https://www.cnblogs.com/xinxue/p/6396196.html