返回for循环或外部循环 [英] return in for loop or outside loop

查看:301
本文介绍了返回for循环或外部循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,有人在Java中使用了 return 关键字。我为循环写了一个简单的来验证某个数组是否在数组中。假设 array 是一个长度为n的数组,这是我的代码:

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

现在有人告诉我这不是很好的编程,因为我使用在一个循环内返回语句,这会导致垃圾回收失败。因此,更好的代码将是:

  int i = 0; 
while(i< array.length&&& array [i]!= valueToFind)++ i;
返回i!= array.length;

问题是我不能拿出一个适当的补充,为什么第一个for循环isn这是一个很好的做法。有人可以给我一个费用吗?
解决方案
现在有人告诉我,这是不是很好的编程因为我在循环中使用了return语句,这会导致垃圾回收失败。


这是不正确的,并建议您应该以一定的怀疑态度来对待该人的其他建议。

只有一个返回语句(或者更一般地说,只有一个退出点)对于必须自己管理所有资源的语言来说很重要 - 那样的话可以确保你把所有的清理代码放在一个地方。

它在Java中非常有用:只要你知道你应该返回(以及返回值应该),只要返回。这样一来,阅读起来就更简单了 - 你不需要采取其他方法来确定还会发生什么(除了 finally 块)之外, 。


Today someone attended me to bad use of the return keyword in Java. I had written a simple for loop to validate 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;

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;

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 expenation?

解决方案

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.

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).

这篇关于返回for循环或外部循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆