在 Java 中优雅地避免 NullPointerException [英] Gracefully avoiding NullPointerException in Java

查看:32
本文介绍了在 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天全站免登陆