在Java中正常地避免NullPointerException [英] Gracefully avoiding NullPointerException in Java

查看:181
本文介绍了在Java中正常地避免NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这一行:

if (object.getAttribute("someAttr").equals("true")) { // ....

显然这行是一个潜在的错误,属性可能是 null ,我们将得到一个 NullPointerException 。因此,我们需要将其重构为两种选择之一:

Obviously this line is a potential bug, the attribute might be null and we will get a NullPointerException. So we need to refactor it to one of two choices:

第一个选项

if ("true".equals(object.getAttribute("someAttr"))) { // ....

第二个选项

String attr = object.getAttribute("someAttr");
if (attr != null) {
    if (attr.equals("true")) { // ....

第一个选项是笨拙的阅读,但更简洁,而第二个是意图清楚,但是冗长。

The first option is awkward to read but more concise, while the second one is clear in intent, but verbose.

您更喜欢哪个选项的可读性?

Which option do you prefer in terms of readability?

推荐答案

我一直使用

if ("true".equals(object.getAttribute("someAttr"))) { // ....

因为虽然读起来有点难度,但是很简单,我认为它足够可读,所以你很容易习惯它

because although it is a little more difficult to read it's much less verbose and I think it's readable enough so you get used to it very easily

这篇关于在Java中正常地避免NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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