我对这被认为是一种好习惯感到困惑 - 这种决策语言是否依赖?假设我有以下Java代码:
public class Stack {
public Integer pop() {
if (isEmpty()) return null; // or some exception maybe?
// else get and return the top item in the stack.
};
}
}
Run Code Online (Sandbox Code Playgroud)
该pop方法的客户端需要一些Integer值,那么让客户端知道堆栈为空的最佳方法是什么?
返回null或默认值通常是一种不好的做法,应该首选异常。原因是,当出现问题时,你应该始终努力尽快失败。如果您返回null,则会在代码中的其他位置发生错误,并且 API 的用户将很难找到问题所在。这称为快速失败。
此经验法则的一个例外是,当您的 API 将使用户依赖异常进行流量控制时,因此,如果您的堆栈不支持isEmpty(),那么异常在这里不是一个好主意。如果您的堆栈仅允许peek()、pop()和add()- 由于某种原因,isEmpty()不允许成为 API 的一部分。
对于这两种方法,用户的代码会发生什么情况?
选项 1 - 使用null:
Integer x = stack.pop();
if (x != null) {
//do something with x
}
Run Code Online (Sandbox Code Playgroud)
选项 2 - 使用异常:
Integer x = null;
try {
x = stack.pop();
} catch (MyException e) { }
//do something with x
Run Code Online (Sandbox Code Playgroud)
第二个实际上是使用异常机制进行流量控制——这是API设计中的一个很大的缺陷。
| 归档时间: |
|
| 查看次数: |
686 次 |
| 最近记录: |