[The Art of Readable Code]拆分超长表达式
2012-12-22 10:35
543 查看
第八章 拆分超长表达式
用做解释变量(总结变量)
在判断语句中可以使用,如:if ( request.user.id == document.owner.id) { // ... }
变成:
bool user_owns_document = request.user.id == document.owner.id; if ( user_owns_document ) { // ... }
user_owns_document就是一个总结变量,这样会让团队其他成员减少读懂这段代码的时间.
使用德摩根定理
not (a or b or c) <=> (not a) and (not b) and (not c);not (a and b and c) <=> (not a) or (not b) or (not c);
一个简单的小结:“分别取反,转换与/或”,反向操作是“提取反向因子”;如:
if (!(file_exist && !is_protected)) log("Cound not read file.");
改为:
if (!file_exist || is_protected)) log("Cound not read file.");
滥用短路逻辑
if (a || b) { //... }
如果a 为真,就不会计算b
与复杂的逻辑战斗
判断Range 边界值的时候,要特别注意是否需要等号
找到更优雅的方式
bool Range:OverlapWith(Range other) { // Check if 'begin' or 'end' falls inside 'other'. return (begin >= other.begin && begin <= other.end) || (end >= other.begin && end <= other.end) || (begin <= other.begin && end >= other.end); }
改为:
bool Range:OverlapWith(Range other) { // Check if 'begin' or 'end' falls inside 'other'. if (other.end <= begin) return flase; if (other.begin >= end) return flase; return true; }
拆分巨大的语句
遵循DRY(Don't Repeat Yourself) 原则遇到重复的表达式,可以将他们抽象成函数,或者定义宏
相关文章推荐
- 晒书有礼!《编写可读代码的艺术》(The Art of Readable Code)晒书有礼活动进行中
- <The Art of Readable Code> 笔记二 (上)
- 晒书有礼!《编写可读代码的艺术》(The Art of Readable Code)晒书有礼活动进行中
- (Notes) The Art of Readable Code------1.Preface
- 读书笔记之《The Art of Readable Code》part 1
- <The Art of Readable Code> 笔记一
- 读书笔记之《The Art of Readable Code》Part 3
- <The Art of Readable Code> 笔记二 (上)
- <The Art of Readable Code> 笔记二 (下)
- <The Art of Readable Code> 笔记二 (上)
- <The Art of Readable Code> 笔记二 (上)
- <The Art of Readable Code> 笔记二 (上)
- The Art of Readable Code
- <The Art of Readable Code> 笔记二 (上)
- 读书笔记之《The Art of Readable Code》Part 2
- The Art of Writing Shellcode, by smiler
- Codeforces Round VK Cup 2015 - Round 1 (unofficial online mirror, Div. 1 only)E. The Art of Dealing with ATM 暴力出奇迹!
- the art or readable code读后感
- God of the code – Virtual Machine(代码的上帝 - 虚拟机)
- julycoding/The-Art-Of-Programming-By-July