java - 空检查的频率和位置
问题描述
我试图避免过度的空检查,但同时我想在需要使代码健壮时进行空检查。但有时我觉得它开始变得如此具有防御性,因为我没有实现 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.
}
解决方案
一般来说,当我控制调用时,我从不检查空值,但如果我的代码可以被其他人调用,我会强制检查,因为你在谈论 API 规范,你可以检查输入参数并抛出 IllegalArgumentException。
当然,这不是必需的,大多数时候,当您拥有 NPE 时,某处存在潜在的错误,但是如果您无法完全控制调用,则肯定需要一些额外的努力。(特别是如果您的 API 会被频繁调用,您需要一些东西来帮助您跟踪/识别错误的调用模式)。
在设计 API 时,除了架构本身之外,您还必须关注维护/故障排除和安全性,特别是如果 API 是公开的(这意味着还要清理每个参数)。
推荐阅读
- amazon-web-services - 从 ebextension 脚本回显字符串
- typescript - 在打字稿中,我可以使用函数中传递的参数之一作为函数内部的类型吗
- angular - 农业网格中的多选下拉菜单
- javascript - 程序找到移动到前面的最小数量以排列数组中的项目并对其进行排序
- binary - 使用直接方式的二进制减法
- r - R基础中的Dcast重复
- c# - 如何对包含每个用户的赢和输数据的 json 作为 C# 中的键进行排序?
- java - 我在 java 中的应用程序抛出一个异常,上面写着 Invalid BSON field name Name
- typo3 - 如何禁用/隐藏列表记录的隐藏/取消隐藏按钮
- apache-spark - DataFrame.withColumn() 使用定制化 UDF 的管道运行速度非常慢