您的位置:首页 > 其它

[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) 原则
遇到重复的表达式,可以将他们抽象成函数,或者定义宏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: