有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java返回入for循环或外循环

今天,有人告诉我Java中return关键字的错误用法。我编写了一个简单的for循环,以验证数组中是否存在某些内容。假设array是一个长度为n的数组,这是我的代码:

for (int i = 0; i < array.length; ++i) {
    if (array[i] == valueToFind) {
        return true;
    }
}
return false;

现在有人告诉我,这不是很好的编程,因为我在循环中使用return语句,这会导致垃圾收集出现故障。因此,更好的代码应该是:

int i = 0;
while (i < array.length && array[i] != valueToFind) {
    ++i;
}
return i != array.length;

问题是,我无法正确解释为什么第一个for循环不是一个好的实践。谁能给我解释一下吗


共 (6) 个答案

  1. # 1 楼答案

    一些人认为一个方法应该有一个单一的出口点(例如,只有一个^{)。就我个人而言,我认为试图坚持这一规则会产生更难阅读的代码。在你的例子中,一旦你找到你要找的东西,立即返回,它很清楚,而且很有效

    Quoting the C2 wiki:

    The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.

    Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.

  2. # 2 楼答案

    代码在这两种情况下都有效(即编译和执行)

    我在Uni的一位讲师告诉我们,在任何循环中使用continuereturn语句是不可取的。这样做的原因是,在检查代码时,无法立即确定循环的整个长度是否会被执行,或者returncontinue是否会生效

    有关示例,请参见Why is continue inside a loop a bad idea?

    需要记住的关键点是,对于这样的简单场景,这并不重要(IMO),但是当您有复杂的逻辑来确定返回值时,如果您有一个而不是几个返回语句,那么代码“通常”更具可读性

    关于垃圾收集,我不知道为什么这会成为一个问题

  3. # 3 楼答案

    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.

    那是一堆垃圾。方法内部的所有内容都将被清除,除非类或其他地方有其他对它的引用(这就是封装很重要的原因)。根据经验,通常最好只使用一个return语句,因为它更容易确定方法将退出的位置

    就我个人而言,我会写:

    Boolean retVal = false;
    for(int i=0; i<array.length; ++i){
        if(array[i]==valueToFind) {
            retVal = true;
            break; //Break immediately helps if you are looking through a big array
        }
    }
    return retVal;
    
  4. # 4 楼答案

    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.

    这是不正确的,并且建议你应该以一定程度的怀疑态度对待那个人的其他建议

    “只有一个返回语句”(或者更一般地说,只有一个退出点)在需要自己管理所有资源的语言中是非常重要的,这样你就可以确保把所有清理代码放在一个地方

    它在Java中的用处要小得多:只要知道应该返回(以及返回值应该是什么),就返回。这样的话,阅读起来就更简单了——你不必接受该方法的任何其他部分来计算出还会发生什么(除了finally块)

  5. # 5 楼答案

    所有语言中都有提倡在任何函数中使用单一返回语句的方法。尽管在某些代码中不可能做到这一点,但有些人确实努力做到这一点,然而,这可能会使代码变得更复杂(比如在更多的代码行中),但另一方面,更容易理解(比如在逻辑流中)

    这不会以任何方式扰乱垃圾收集

    更好的方法是设置一个布尔值,如果你想听他的话

    boolean flag = false;
    for(int i=0; i<array.length; ++i){
        if(array[i] == valueToFind) {
            flag = true;
            break;
        }
    }
    return flag;
    
  6. # 6 楼答案

    因为GC没有问题。我更喜欢这个

    for(int i=0; i<array.length; ++i){
        if(array[i] == valueToFind)
            return true;
    }