如何在 getter 链中跟踪 NullPointerException [英] How to trace a NullPointerException in a chain of getters

查看:31
本文介绍了如何在 getter 链中跟踪 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在这样的调用中得到 NullPointerException:

If I get a NullPointerException in a call like this:

someObject.getSomething().getSomethingElse().
    getAnotherThing().getYetAnotherObject().getValue();

我得到一个相当无用的异常文本,例如:

I get a rather useless exception text like:

Exception in thread "main" java.lang.NullPointerException
at package.SomeClass.someMethod(SomeClass.java:12)

我发现很难找出哪个调用实际上返回了 null,经常发现自己将代码重构为这样的:

I find it rather hard to find out which call actually returned null, often finding myself refactoring the code to something like this:

Foo ret1 = someObject.getSomething();
Bar ret2 = ret1.getSomethingElse();
Baz ret3 = ret2.getAnotherThing();
Bam ret4 = ret3.getYetAnotherOject();
int ret5 = ret4.getValue();

然后等待更具描述性的 NullPointerException 告诉我要查找哪一行.

and then waiting for a more descriptive NullPointerException that tells me which line to look for.

你们中的一些人可能会争辩说,连接 getter 是一种糟糕的风格,无论如何都应该避免,但我的问题是:我可以在不更改代码的情况下找到错误吗?

Some of you might argue that concatenating getters is bad style and should be avoided anyway, but my Question is: Can I find the bug without changing the code?

提示:我正在使用 eclipse 并且我知道调试器是什么,但我无法弄清楚如何将其应用于问题.

Hint: I'm using eclipse and I know what a debugger is, but I can't figuer out how to apply it to the problem.

我对答案的总结:
有些答案告诉我,我不应该一个接一个地链接 getter,有些答案告诉我,如果我不遵守该建议,如何调试我的代码.

My conclusion on the answers:
Some answers told me that I should not chain getters one after another, some answers showed my how to debug my code if I disobeyed that advice.

我已经接受了一个答案,该答案教会了我何时链接 getter:

I've accepted an answer that taught me exactly when to chain getters:

  • 如果它们不能返回 null,只要你喜欢就可以将它们链接起来.无需检查 != null,无需担心 NullPointerExceptions(请注意,链接仍然违反了迪米特法则,但我可以接受)
  • 如果它们可能返回 null,永远不要链接它们,并检查每个可能返回 null 的 null 值

这使得任何关于实际调试的好建议都变得毫无用处.

This makes any good advice on actual debugging useless.

推荐答案

答案取决于您如何看待 getter(的契约).如果他们可能返回 null 你真的应该每次都检查返回值.如果 getter 不应返回 null,则 getter 应包含检查并抛出异常 (IllegalStateException?) 而不是返回 null,即您承诺永远不会回来.堆栈跟踪会将您指向确切的 getter.您甚至可以将 getter 发现的意外状态放在异常消息中.

The answer depends on how you view (the contract of) your getters. If they may return null you should really check the return value each time. If the getter should not return null, the getter should contain a check and throw an exception (IllegalStateException?) instead of returning null, that you promised never to return. The stacktrace will point you to the exact getter. You could even put the unexpected state your getter found in the exception message.

这篇关于如何在 getter 链中跟踪 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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