[The Art of Readable Code]拆分超长表达式

第八章 拆分超长表达式

用做解释变量(总结变量)

在判断语句中可以使用,如:

if ( request.user.id == document.owner.id) {
    // ...
}

变成:

bool user_owns_document = request.user.id == document.owner.id;
if ( user_owns_document ) {
    // ...
}

user_owns_document就是一个总结变量,这样会让团队其他成员减少读懂这段代码的时间.

使用德摩根定理
  1. not (a or b or c) <=> (not a) and (not b) and (not c);
  2. 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) 原则
  • 遇到重复的表达式,可以将他们抽象成函数,或者定义宏


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值