我必须编写一个函数来从链接列表(我的,而不是集合框架的元素)中删除一个元素,所以我的第一次尝试是:
public void remove(E element) {
Cell<E> cell = sentinel;
int i = 0;
while (i < count) {
if (cell.getElement().equals(element)) {
cell.getPrevious().setNext(cell.getNext());
--count;
return;
}
++i;
cell = cell.getNext();
}
}我的问题是:像这样使用return是不是很好?更广泛地说,当条件被检查并且没有必要运行以下指令时,我认为使用return是有意义的:
void func() {
while (condition) {
if (something) {
instructions;
return;
}
more instructions;
}
}但是,由于它不是很容易读,而且每个人都说,在java中,可读性是最重要的,所以我不得不考虑另一种方法。因此,我更改了条件,并使用了额外的布尔值。
public void remove(E element) {
boolean found = false;
Cell<E> cell = sentinel;
int i = 0;
while (!found && i < count) {
if (cell.getElement().equals(element))
found = true;
else {
++i;
cell = cell.getNext();
}
}
if (found) {
cell.getPrevious().setNext(cell.getNext());
--count;
}
}这样,就没有奇怪的return,指令只有在必要时才会执行。如果我再次面对这种情况,我想我将不得不像这样重写循环。也许我完全错了,第一种方法更好。你觉得它怎么样?
发布于 2016-02-13 11:45:21
在我看来,如果不是太复杂的话,早点回来是很好的。类似于使用break语句提前从循环中分离出来。
你可以看看这个关于程序员的问题,他们每个人都提出了有效的观点。https://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement
发布于 2016-02-13 12:42:03
函数中的独立逻辑,有的只读取,有的只改变状态。如果您有一个查找功能,那么在搜索过程中返回是很清楚的。
例如
public void remove(E element) {
Cell<E> cell = FindCell(element);
if (cell != null)
RemoveCell(cell);
}
private <E> FindCell(E element) {
<E> cell = sentinel;
int i = 0;
while (i < count) {
if (cell.getElement().equals(element)) {
return cell;
}
++i;
cell = cell.getNext();
}
return null;
}
private void RemoveCell(<E> cell) {
cell.getPrevious().setNext(cell.getNext());
--count;
}这种分离给了你一些好处。您可以根据需要多次调用只读函数(可能在并行线程中),而且您肯定知道什么都不会发生。例如,C++具有const函数。
当您需要中断两个或多个嵌套循环时,返回非常方便。
发布于 2016-02-13 12:32:47
这完全是一个选择的问题,他们所说的走出循环的任何一种方式都没有错,只需要记住两件事。
当您不想在该特定方法的外部循环上执行代码的其余部分并返回到调用者时,可以使用返回。 当您不想再执行循环时,可以使用布尔
true or false,但是您仍然希望继续使用该方法中的其余代码。
https://stackoverflow.com/questions/35379395
复制相似问题