首页 > 解决方案 > 空检查的频率和位置

问题描述

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

让我举一个我的困惑开始的虚拟示例:

这是界面的默认功能:

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.
}

标签: javaapiclean-architecture

解决方案


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

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

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


推荐阅读