在Java中回避潜在的空指针警告的一种方法

It’s silly to hate null pointer exceptions. If you pay attention to compiler warnings, it’s unlikely that a null pointer exception will catch you by surprise in a production context.

讨厌空指针异常是愚蠢的。 如果您注意编译器警告,则在生产环境中,空指针异常不太可能使您措手不及。

Test-driven development is also a big help in that department. A null pointer exception in a development context is then just a part of the process, not something to fear, much less hate.

测试驱动的开发对该部门也有很大帮助。 因此,在开发环境中,空指针异常只是过程的一部分,不必担心,更不用说讨厌了。

Still, the “dereferencing possible null pointer” warning can be annoying at times. If you don’t want to get bogged down in a major digression, you can sidestep the warning with an assertion.

尽管如此,“取消可能的空指针”警告有时还是很烦人的。 如果您不想陷入重大困境,可以通过声明来避免警告。

On the line before the possible null pointer warning, assert that the pertinent object is in fact not null. This should clear the warning.

在可能的空指针警告之前的那一行,断言相关对象实际上不是空的。 这应该清除警告。

It may not be the absolute best solution, but it helps defer the problem to when you’ve had more time to think about it.

它可能不是绝对最佳的解决方案,但可以帮助您将问题推迟到您有更多时间考虑它时。

I will give an example from one of my actual projects, when I was refactoring my Algebraic Integer Calculator project last week. You don’t need to know too much about math to follow along.

当我上周重构我的代数整数计算器项目时,我将以一个实际项目为例。 您无需对数学了解太多即可继续学习。

I deleted a redundant function in a utility class. I had been hesitant to do that because I thought it would cause a hundred compilation errors throughout the project. It actually only caused a couple of errors.

我在实用程序类中删除了冗余功能。 我一直很犹豫,因为我认为这会在整个项目中造成100个编译错误。 实际上,它仅导致了几个错误。

That included a compilation error in a custom exception, which I fixed with one little adjustment. While I was at it, I figured I’d do a little refactoring of the custom exception.

其中包括自定义异常中的编译错误,我对此进行了一些小的调整。 当我这样做时,我想我会对自定义异常进行一些重构。

Thanks to a handy new function in the utility class, I was able to take advantage of the polymorphism I’ve worked so much on in the project, and reduce one level of indentation for some nested If-Else statements in the custom exception I was looking at.

多亏了实用程序类中的一个方便的新函数,我得以利用我在项目中进行了大量工作的多态性,并在自定义异常中为某些嵌套的If-Else语句减少了缩进级别看着。

Some programmers say you should never ever use If-Else. I’m not that dogmatic, though I do want to avoid excessive nesting of If-Else. So if I can see a good way to refactor such nesting out, I’ll go for it.

一些程序员说您永远不要使用If-Else。 尽管我确实想避免If-Else的过多嵌套,但我并不是那么教条。 因此,如果我能看到重构这种嵌套的好方法,那么我会去做的。

In this case, though, the now unnecessary If statement was an instanceof check which protected another If statement a few lines down from the possibility of trying to operate on a null object.

但是,在这种情况下,现在不再需要的If语句是一个instanceof检查,它保护了另一个If语句几行以免尝试对空对象进行操作。

Without that earlier If statement, there’s nothing to guarantee to the compiler that the local variable workingRing is not null. In turn workingRing is a cast of the field initRing, which is of a fairly general type defined by an interface.

没有较早的If语句,就无法向编译器保证局部变量workingRing不为null。 反过来, workingRing是字段initRing ,它是由接口定义的相当通用的类型。

So NetBeans quite rightly relays the compiler warning that workingRing is a “possible null pointer.” But I’m quite sure that workingRing is in fact never null. On the other hand, computers are much better at keeping track of state than humans are, so a null here might be possible somehow…

因此,NetBeans非常正确地向编译器workingRing了警告,警告workingRing是“可能的空指针”。 但是我很确定, workingRing实际上永远不会为空。 另一方面,计算机在跟踪状态方面比人类要好得多,因此以某种方式可能会出现空值……

As I started to backtrack through the process that an object goes through to become workingRing, I realized that I had been completely sidetracked from what I had wanted to get done on the utility class that day.

当我开始回溯一个对象变为workingRing ,我意识到我已经完全偏离了那天我想要在实用程序类上完成的工作。

So I thought maybe I should just put in a To Do comment and set it aside. And then I got the idea to put in an assertion:

所以我想也许我应该只添加一个“待办事项”注释并将其放在一边。 然后我想到了一个断言:

        assert workingRing != null : "Ring must not be null";
if (workingRing.hasHalfIntegers()) {
int topPointA, topPointB;
// etc., etc.
}

That clears the warning. If workingRing somehow happens to be null, the assertion will fail and an AssertionError will be thrown, crashing the program before trying to check whether workingRing has “half-integers.”

这清除了警告。 如果workingRing以某种方式碰巧为null,则断言将失败并且将引发AssertionError ,从而在尝试检查workingRing是否具有“半整数”之前使程序崩溃。

The error message will be “Ring must not be null,” which is hopefully more helpful than a NullPointerException with null message.

错误消息将为“ Ring不能为空”,希望它比带有null消息的NullPointerException更有用。

However, do keep in mind that the Java Virtual Machine (JVM) generally runs with assertions turned off. This means that if workingRing happens to be null somehow, the assertion will be skipped over and the next line will cause one of those much dreaded null pointer exceptions.

但是,请记住,Java虚拟机(JVM)通常在断言关闭的情况下运行。 这意味着,如果workingRing碰巧为null,则断言将被跳过,并且下一行将导致那些令人恐惧的null指针异常之一。

Essentially I have sidestepped the compiler warning. Maybe later on I’ll think of a way to make the compiler understand that workingRing is never null. For now, though, this will do.

本质上,我回避了编译器警告。 也许以后,我会考虑一种使编译器理解workingRing永远不会为null的方法。 不过,到目前为止,这确实可以做到。

And of course it’s also possible that I have in fact overlooked something and there really is a way a null workingRing could fall through the cracks.

当然,也有可能我实际上忽略了某些东西,并且确实有一种方法可以使null workingRing掉入裂缝。

One more thing, though: assertions are turned on for JUnit tests, and then it doesn’t matter if the assertion occurs in Source Packages or Test Packages.

但是,还有一件事:为JUnit测试打开了断言,然后断言是发生在Source Packages还是Test Packages中都没有关系。

If the class under test causes an AssertionError to be thrown, that will be wrapped into a JUnit AssertionFailedError. And then JUnit will report that as a test that caused an error.

如果被测类导致引发AssertionError ,则将其包装到JUnit AssertionFailedError 。 然后,JUnit会将其报告为导致错误的测试。

Ultimately, the important thing isn’t whether a null pointer causes an AssertionError or a NullPointerException. The important thing is to catch these problems in development, not production.

最终,重要的不是空指针是否导致AssertionErrorNullPointerException 。 重要的是要在开发而不是生产中抓住这些问题。

翻译自: https://medium.com/swlh/one-way-to-sidestep-potential-null-pointer-warning-in-java-ffef431394a8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值