根据 Algorithms, Part 1,我正在 Java 上编写 Deque
类在 Coursera 上。目前我的基于数组的 Deque
有方法 removeLast()
:
public Item removeLast() {
if (size() == array.length / 4) {
resize(array.length / 2);
}
if (head != tail) {
Item tmp = array[--head];
array[head] = null;
return tmp;
}
throw new NoSuchElementException("Stack underflow");
}
如果 head == tail
意味着 Deque
是空的,我抛出异常,根据作业规范,在方法结束时而不是 return
声明。此代码给出了关于不变量的直接意图(head != tail
)。
另一方面,方法可以这样重写:
public Item removeLastRewritten() {
if (size() == array.length / 4) {
resize(array.length / 2);
}
if (head == tail) {
throw new NoSuchElementException("Stack underflow");
}
Item tmp = array[--head];
array[head] = null;
return tmp;
}
在我看来removeLast
写的比较清楚,原因如下:
- 坚持悲观的场景——
总是失败,只有当...
这是更可靠的方法,尤其是当方法代码将扩大并变得更复杂时。 - 在不变的
tail != head
和后续的if {}
代码块之间提供更清晰的链接。
我有以下问题:
- 哪种方法更好?
- 像
removeLast
这样的写法是否被认为是一种合适的/好的做法? - Java 的最佳实践是什么?有没有关于它的代码风格(我找不到)?
最佳答案
没有错误的答案。在 GrepCode 中,您可以找到您建议的每一种口味:
- 在带有 != 运算符的 if 内和方法的末尾:
E java.util.PriorityQueue.next()
public E More ...next() {
if (... != ...)
throw new ConcurrentModificationException();
...
if (...) {
return lastRetElt;
}
throw new NoSuchElementException();
}
- 在带有 == 运算符的 if 中
E org.fluentlenium.core.domain.FluentList.first()
public E More ...first() {
if (this.size() == 0) {
throw new NoSuchElementException("Element not found");
}
return this.get(0);
}
关于java - 在 Java 方法中抛出异常而不是返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31604537/