gpt4 book ai didi

java - 进行 Null 检查的频率和位置

转载 作者:行者123 更新时间:2023-12-03 22:16:19 25 4
gpt4 key购买 nike

我试图避免过度执行空值检查,但同时我想在需要使代码健壮的时候进行空值检查。但有时我觉得它开始变得如此防御,因为我没有实现 API。然后我避免了一些空检查,但是当我开始单元测试时,它开始总是等待运行时异常。什么是正确的做法,如何感受平衡。以下是我到目前为止收集的笔记:

  • 避免在实例类的私有(private)方法中进行不必要的空值检查,因为之前会进行适当的空值检查,并且实例类对此负责,而不是每个函数
  • 在公共(public)方法中进行空检查,并在契约(Contract)中解释函数行为以供公共(public)使用
  • 在构造函数中进行空值检查

让我举一个让我感到困惑的虚拟例子:

这是接口(interface)的默认函数:

default void someFunction() {

// instantiaded foo and filters
foo = processFoo(foo, filters);

// do some operations with foo
// null check if processFoo's contract returns null (description in the implementation)

}

实现:

Foo processFoo(foo, filters) {
// Should I null check foo and filters?

// Operations with foo.someFields
// Operations with filters.someFields

return foo; // If I null check then I should return some exception or null to the caller function.
// If I don't null check just return received foo.
}

最佳答案

一般来说,当我控制调用时,我从不检查空值,但如果我的代码可以被其他人调用,我会强制执行检查,因为你在谈论 API 规范,你可能会检查输入参数并抛出 IllegalArgumentException。

当然,这不是必需的,大多数时候,当您有 NPE 时,某处存在潜在的错误,但是如果您不能完全控制调用,您肯定需要一些额外的努力。 (特别是如果您的 API 将被频繁调用,您需要一些东西来帮助您跟踪/识别错误的调用模式)。

在设计 API 时,除了架构本身,您还必须关注维护/故障排除和安全性,特别是如果 API 是公开的(这也意味着清理每个参数)。

关于java - 进行 Null 检查的频率和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54018526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com