您的位置:首页 > 其它

<The Art of Readable Code> 笔记一

2017-02-14 11:27 543 查看

第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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: