防御式编程 Java重构之卫语句

399 篇文章 12 订阅
143 篇文章 1 订阅

使用卫语句

对于非法输入的检查我们通常会使用 if…else 去做判断,但往往在判断过程中由于参数对象的层次结构会一层一层展开判断。

public void doSomething(DomainA a) {
  if (a != null) {
        assignAction;
    if (a.getB() != null) {
      otherAction;
      if (a.getB().getC() instanceof DomainC) {
        doSomethingB();
        doSomethingA();
        doSomthingC();
      }
    }
  }
}

上边的嵌套判断的代码我相信很多人都见过或者写过,这样做虽然做到了基本的防御式编程,但是也把丑陋引了进来。《Java 开发手册》中建议我们碰到这样的情况使用卫语句的方式处理。什么是卫语句?我们给出个例子来说明什么是卫语句。

public void doSomething(DomainA a) {
    if (a == null) {
        return ; //log some errorA
    }
    if (a.getB() == null) {
        return ; //log some errorB
    }
    if (!(a.getB().getC instanceof DomainC)) {
        return ;//log some errorC
    }
    assignAction;
    otherAction
    doSomethingA();
    doSomethingB();
    doSomthingC();
}

方法中的条件逻辑使人难以看清正常的分支执行路径,所谓的卫语句的做法就是将复杂的嵌套表达式拆分成多个表达式,我们使用卫语句表现所有特殊情况。

备注

如果考虑到程序逻辑的正确性的话,上面代码使用卫语句重构后的代码如下

public void doSomething(DomainA a) {
    if (a == null) {
        return ; //log some errorA
    }
    assignAction;
	
    if (a.getB() == null) {
        return ; //log some errorB
    }
    otherAction;
	
    if (!(a.getB().getC instanceof DomainC)) {
        return ;//log some errorC
    }
    doSomethingA();
    doSomethingB();
    doSomthingC();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值