FALSE_IT

本文讲一个实用的语法糖(suger),很不错,攻克了我实际工作中的问题。

如果你写了这样一个类:

class Executor {
  int step1();
  void step2();
  int step3();
}

#define FAIL -1

int main() {
  // 使用Executor。调用顺序必须是123
  Executor exec;
  if (FAIL == exec.step1()) {
       log('error');
  } else {
      exec.step2();   // 不能通过if调用,由于返回值是void
      if (FAIL == exec.step3()) {
         log('error');
      }
  }
 }

就由于一个void返回,让代码一下子别扭了,丑不丑?
如果能这样写该多好:

  Executor exec;
  if (FAIL == exec.step1()) {
       log('error');
  } else if (FAIL == exec.step2()) {
       log('error');
  } else if (FAIL == exec.step3()) {
       log('error');
  }

事实上办法是有的。仅仅须要写这样一个宏:

\#define FALSE_IT(stmt) ({ (stmt); false; })
  Executor exec;
  if (SUCCESS == exec.step1()) {
       log('error');
  } else if (FALSE_IT(exec.step2()) {   // 应用FALSE_IT宏
       log('error');  // won't be here
  } else if (FAIL == exec.step3()) {
       log('error');
  }

美丽不!

本方法来自阿里巴巴 OceanBase团队 @符风 同学。

posted on 2017-07-22 09:00  slgkaifa  阅读(171)  评论(0编辑  收藏  举报

导航