有没有 ?.Java 执行空指针检查的运算符? [英] Is there a ?. operator for Java to perform null pointer checking?

查看:51
本文介绍了有没有 ?.Java 执行空指针检查的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编码时,我对空检查感到沮丧.尤其是在编码数据结构时!

When I code I am frustrated with null checks. Especially while coding data structures!

我必须这样做

String val;
if(a != null && a.child != null)
    val = a.child.getValue();
else
    val = null;

有点像这样......

Something sort of this...

有像 ? 的运算符.(这是C#的一部分)为Java减轻负担?

С# 示例:

String val = a?.child?.getValue();

推荐答案

没有 ?.Java 中的运算符,因此,正如 Hari 指出的那样,您必须以冗长"的方式做事.然而,人们可能会争辩说这是一件好事,因为它不鼓励使用空值.

There is no ?. operator in Java, so, as Hari notes, you have to do things the "long winded" way. However, one could argue that this is a good thing, as it discourages the use of nulls.

例如,在 OP 的代码中,如果 a 或它的孩子不存在,为什么要将 val 设置为 null?让我们假设这是一个函数并且 val 被返回.这是一种代码异味:它只是将再次空检查的要求推给了代码的用户.它变成了空检查的无休止循环,完全使代码混乱并混淆了逻辑,因为维护程序员往往无法判断这是否是合理的逻辑,或者一个偏执的前程序员正在悄悄地忽略错误.不要模仿 PHP!.引用那篇精彩的咆哮:

For example, in OP's code, why are you setting val to null if a or it's child is not there? Let's assume that this is a function and val gets returned. This is a code smell: it just pushes the requirement for yet another null check to users of your code. It becomes an endless cycle of null checks, completely cluttering the code and confusing the logic, because maintenance programmers often can't tell if this is legitimate logic, or a paranoid former programmer is quietly ignoring errors. Don't mimic PHP!. Quoting from that excellent rant:

当面临做一些荒谬的事情或因错误而中止时,它 (PHP) 会做一些荒谬的事情."

"When faced with either doing something nonsensical or aborting with an error, it (PHP) will do something nonsensical."

PHP 做出了一个糟糕的设计选择.因错误而中止比做一些无意义的事情要好得多.

PHP makes a horrible design choice. It is far better to abort with an error than do something nonsensical.

相反,您应该提出以下问题:

Instead, you should be asking questions like:

  1. a 为空是什么意思?这是编程错误吗?如果是这样,抛出一些 RuntimeException/IllegalArgumentException.如果这是关键代码并且你不能失败",至少记录你正在掩盖一些可疑的东西,这样也许它会得到修复.
  2. 如果 a.child.getValue() 本身返回 null 怎么办? 我的调用者将如何区分该 null 和a or child is null"null 之间的区别?他们不能.
  3. 如果有一个好的默认值,就使用它.如果您使用的是集合或数组,不要传递 null 来表示空".传递一个 Collections.emptyXXX(),例如空列表,或空数组.与其将 String 设置为 null,不如考虑将其设置为空字符串 "".顺便说一句,这使您的 hashCode()、equals() 和 compareTo() 更加简单!
  4. 使用空对象模式..如果 a 是 Foo 的一个实例,则定义一个静态 final Foo.NULL,它确实有一个孩子,其值本身就是nullish"——null 或".
  1. What does it mean for a to be null? Is this a programming error? If so, throw some RuntimeException / IllegalArgumentException. If this is critical code and you "can't fail", at least log that you are papering over something fishy, so maybe it will get fixed.
  2. What if a.child.getValue() itself returns null? How will my caller tell the difference between that null and the "a or child is null" null? They can't.
  3. If there is a good default value, use it. If you are using a Collection or Array, don't pass null to mean "empty". Pass a Collections.emptyXXX(), e.g. an emptyList, or an empty array. Instead of setting a String to null, consider setting it to the empty string "". BTW, this makes your hashCode(), equals(), and compareTo() much simpler!
  4. Use the Null Object Pattern.. If a is an instance of a Foo, define a static final Foo.NULL which does have a child whose value is itself something "nullish" - either null or "".

有时你真的不能做任何这些事情.参数为空是有正当理由的,或者您必须允许向后兼容以前的不良设计或第 3 方库.IMO,这应该很少见,您应该记录发生的情况.也许您应该返回 null(或 0)以外的其他值来反映这一点.例如

Sometimes you really can't do any of these things. There are valid reasons for arguments to be null, or you must allow for backwards compatibility with a previous bad design or 3rd party library. IMO, this should be rare, and you should document what happens. And maybe you should return something other than null (or 0) to reflect this. For example

/**
   countPeople
   @param  node  null means the foobar can't connect to the database, 
   @return       Foobar.ERR_NO_DB if node is null
*/

在 OP 的示例中,它看起来像是某种 XML 节点,Java XML 接口非常庞大,为其中一个创建一个好的 NULL 对象将是一项艰巨的任务.(嗯,也许是一个不错的小开源项目?).但是,在这种情况下,您可能会经常调用 a.child.getValue().编写一个小实用函数来处理这个问题并处理空值.不是到处都是冗长的空检查,至少它们被封装在一些实用方法中.干燥.而且,可以说,检查冗长的事实鼓励你做一个更好的设计.所以缺少?.运营商是个好东西,对吧?:-)

In OP's example, it looks like a may be some sort of XML node, and the Java XML interfaces are huge and creating a good NULL object for one of them would be a huge undertaking. (Hmm, maybe a good little open source project?). However, in that case, you will likely be calling a.child.getValue() a lot. Write a little utility function to handle this and handle the nulls. Instead of long winded null checks everywhere, at least they are encapsulated in a few utility methods. DRY. And, arguably the fact that the checks are long winded, encouraged you to do a better design. So the lack of the ?. operator was a good thing, right? :-)

这篇关于有没有 ?.Java 执行空指针检查的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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