Java:空检查的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20693058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:37:40  来源:igfitidea点击:

Java: Best practice for null check

java

提问by Alfred

I know that NULL check for every arguments in a public API is good practice in java. But just curious, do we need do such NULL check in the front of all methods. There are definitely values for doing this: catching error earlier and providing better error message. But is it worthy, I mean doing the same NULL check in all methods seems too tedious. If that is needed, why JVM cannot the job by default.

我知道对公共 API 中的每个参数进行 NULL 检查是 Java 中的好习惯。但只是好奇,我们是否需要在所有方法的前面做这样的 NULL 检查。这样做肯定有价值:更早地捕获错误并提供更好的错误消息。但是值得吗,我的意思是在所有方法中都做同样的 NULL 检查似乎太乏味了。如果需要,为什么默认情况下 JVM 不能执行该作业。

Please share your thoughts.

请分享您的想法。

回答by DerStrom8

Normally it's easiest to simply declare variables or methods so that they never return a null. However, sometimes it's unavoidable, like in some existing methods in the API, and some self-created methods and variables need to have a null value set. Personally I recommend avoiding null values whenever possible--it's always best to declare a variable from the start, or have a method return, for example, a -1 instead of a null if a certain operation fails. In general though, if you know a variable or method may have a null value, you should do a null check at the beginning just to be on the safe side.

通常,最简单的方法是简单地声明变量或方法,以便它们永远不会返回空值。但是,有时它是不可避免的,例如在API中的一些现有方法中,并且一些自创的方法和变量需要设置空值。我个人建议尽可能避免使用 null 值——最好从一开始就声明一个变量,或者让方法返回,例如,如果某个操作失败,则返回 -1 而不是 null。但是一般来说,如果您知道一个变量或方法可能有一个空值,您应该在开始时进行空检查,以确保安全。

Hope this helps, and I wish you the best of luck!

希望这会有所帮助,祝你好运!

回答by Robin Green

If that is needed, why JVM cannot the job by default.

如果需要,为什么默认情况下 JVM 不能执行该作业。

It does! It checks if the value is null, and if not, throws a NullPointerException. In many cases this is the appropriate behaviour and you do not need to change it.

确实如此!它检查该值是否为空,如果不是,则抛出一个NullPointerException. 在许多情况下,这是适当的行为,您无需更改它。