在java中尝试/ catch vs null检查 [英] try/catch vs null check in java

查看:101
本文介绍了在java中尝试/ catch vs null检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会面对我必须写一段这样的代码(通常它有更多的嵌套if和更复杂的结构,但是对于这个例子来说)

Sometimes I face I must write a piece of code like this (usually it have more nested if and more complex structure but for the example is enought)

public void printIt(Object1 a){
  if (a!=null){
     SubObject b= a.getB();
     if (b!=null){
         SubObject2 c=b.getC();
         if(c!=null){
             c.print();
         }
     }
  }
}

我不需要知道什么是失败的,如果什么是null什么也不做,一种方法可能是

when I dont need to know what failed and if something is null do nothing, an approach could be

public void printIt(Object1 a){
    try{
      a.getB().getC().print();
    }catch (NullPointerException e) {
    }
}

第二种形式如性能或其他类型的问题是否有问题?

Is there something wrong in this second form like performance or other kind of issues?

谢谢

推荐答案

异常版本(类似于使用Groovy的安全导航操作符?。的链)使得很容易采用得墨忒耳定律(或者像我一样)称之为Demeter的强烈建议,并将其作为夜晚的玩物。

The exception version (similar to chains using Groovy's safe-navigation operator ?.) makes it really easy to take the Law of Demeter (or as I call it, Demeter's Strongly-Worded Suggestion) and make it your plaything for the night.

同样,深度嵌套的如果 -statements导致难以阅读的代码,并且在其下面,存在相同的违规,并且这种方法的圈复杂度很高。

Similarly, deeply-nested if-statements leads to difficult-to-read code, and underneath it all, the same "violation" exists, and the cyclomatic complexity of such methods is high.

public void printIt(Object1 a) {
    if (null == a) {
        return;
    }

    SubObject b = a.getB();
    if (null == b) {
        return;
    }

    SubObject2 c = b.getC();
    if (null == c) {
        return;
    }

    c.print();
}

我宁愿在封装的适当位置看到LAM(小辅助方法)检查并完全消除了对问题的需求。

I'd rather see LAMs (Little Auxiliary Methods) in appropriate places that encapsulate the checks and pretty much eliminate the need for the question altogether.

这篇关于在java中尝试/ catch vs null检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆