return in for 循环或外循环 [英] return in for loop or outside loop
问题描述
今天,有人提醒我在 Java 中错误使用了 return
关键字.我编写了一个简单的 for
循环来验证数组中是否存在某些内容.假设 array
是一个长度为 n
的数组,这是我的代码:
Today, someone attended me to bad use of the return
keyword in Java. I had written a simple for
loop to validate that something is in an array. Supposing array
is an array of length n
, this was my code:
for (int i = 0; i < array.length; ++i) {
if (array[i] == valueToFind) {
return true;
}
}
return false;
现在有人告诉我,这不是很好的编程,因为我在循环中使用了 return
语句,这会导致垃圾收集发生故障.因此,更好的代码应该是:
Now someone told me that this is not very good programming because I use the return
statement inside a loop and this would cause garbage collection to malfunction. Therefore, better code would be:
int i = 0;
while (i < array.length && array[i] != valueToFind) {
++i;
}
return i != array.length;
问题是我无法正确解释为什么第一个 for 循环不是一个好习惯.有人可以给我解释一下吗?
The problem is that I can't come up with a proper explenation of why the first for loop isn't a good practice. Can somebody give me an explanation?
推荐答案
现在有人告诉我,这不是很好的编程,因为我在循环中使用了 return 语句,这会导致垃圾收集发生故障.
Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.
这是不正确的,并建议您应该以一定程度的怀疑态度对待来自该人的其他建议.
That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.
只有一个返回语句"(或更一般地说,只有一个退出点)的口头禅在您必须自己管理所有资源的语言中很重要 - 这样您就可以确保将所有清理代码放在一个地方.
The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.
它在 Java 中的用处要小得多:只要您知道应该返回(以及返回值应该是什么),就返回.这样,阅读起来更简单——您不必采用该方法的任何其余部分来计算将要发生的其他事情(除了 finally
块).
It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally
blocks).
这篇关于return in for 循环或外循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!