pat*_*rit 5 language-agnostic scala api-design preconditions scala-collections
我正在设计一个类似这样的API:
// Drop $howMany items from after $from
def dropElements[T](array: Array[T], from: Int, howMany: Int)
Run Code Online (Sandbox Code Playgroud)
预期的行为是howMany应该是非负的,如果howMany为零,它不应该做任何修改.我有两种方法来实现这个:
def dropElements[T](array: Array[T], from: Int, howMany: Int) {
assert(howMany >= 0);
if (howMany == 0) return;
assert(0 <= from && from < array.length);
....
}
Run Code Online (Sandbox Code Playgroud)
要么:
def dropElements[T](array: Array[T], from: Int, howMany: Int) {
assert(howMany >= 0);
assert(0 <= from && from < array.length);
if (howMany == 0) return;
....
}
Run Code Online (Sandbox Code Playgroud)
我赞成第二种方法(预先声明你的先决条件)与第一种方法相比,但有人指出,当howMany = 0时,第一种方法更加尊重要求.
我更喜欢一石二鸟:避免return将方法体放在单个else子句中,并将所有断言放在一起。此外,如果可能的话,断言应该失败并显示有用的消息:
def dropElements[T](array: Array[T], from: Int, howMany: Int): Array[T] =
if (howMany == 0) array
else {
assert(howMany > 0, "howMany must > 0")
assert(from >= 0, "from must >= 0")
assert(from < array.length, s"from must < ${array.length}")
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |