在循环中间返回和/或中断。它可以被接受吗?
假设我们有一个整数数组。我们编写了一个函数来获取数组中第一个指定值的索引,如果数组不包含该值,则获取 -1。
例如,如果 array = { 4, 5, 4, 4, 7 },那么 getFirstIndexOf(4)
将返回 0,getFirstIndexOf(7)
将返回 4,getFirstIndexOf(8)
将返回代码> 会返回-1。
下面,我介绍了编写此函数的三种不同方法。这是一种广泛接受的编码标准,在函数中间返回
,在循环中间中断
都是不好的做法。在我看来,这对他们来说可能是可以接受的用途。
public int getFirstIndexOf(int specifiedNumber) {
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
return i;
}
}
return -1;
}
VS。
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
result = i;
break;
}
}
return result;
}
VS。
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber && result == -1) {
result = i;
}
}
return result;
}
你怎么认为?哪个最好?为什么?也许还有另一种方法可以做到这一点吗?
Suppose we have an array of integers. We've written a function to fetch the index of the first specified value in the array, or -1 if the array does not contain the value..
So for example, if the array = { 4, 5, 4, 4, 7 }
, then getFirstIndexOf(4)
would return 0, getFirstIndexOf(7)
would return 4, and getFirstIndexOf(8)
would return -1.
Below, I have presented three different ways to write this function. It is a widely accepted coding standard that returns
in the middle of functions, and breaks
in the middle of loops are poor practice. It seems to me that this might be an acceptable use for them.
public int getFirstIndexOf(int specifiedNumber) {
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
return i;
}
}
return -1;
}
VS.
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber) {
result = i;
break;
}
}
return result;
}
VS.
public int getFirstIndexOf(int specifiedNumber) {
int result = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] == specifiedNumber && result == -1) {
result = i;
}
}
return result;
}
What do you think? Which is best? Why? Is there perhaps another way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为当您已经找到结果时运行完整循环是很糟糕的做法...
如果您确实想避免使用从循环中间返回,我建议使用“哨兵”来停止循环。
编辑:我讨厌在 StackOverflow 中使用空格来缩进代码...
I think it's poor practice to run a full loop when you have already found your result...
If you really want to avoid using return from the middle of the loop, I would sugest to use a "sentinel" to stop your loop.
edit: I hate to indent code using spaces in StackOverflow...
这就是为什么 do...while & while循环被发明。
根据要求:
That's why do...while & while loop was invented.
As requested: