开发者

Returns and/or breaks in the middle of a loop. Is it ever acceptable?

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 specifie开发者_如何学PythondNumber) {
  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?


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.

public int getFirstIndexOf(int specifiedNumber, int[] array) {

    boolean found = false;
    boolean exit = false;
    int i = 0;
    int arraySize = array.length();

    while(!found && !exit) {
        if(array[i] == specifiedNumber) {
            found = true;
        } else {
            if(i++ > arraySize) {
            exit = true;
            }
        }

    if(found ==true) {
       return i;
    } else {
       return 99999;
    }
}

edit: I hate to indent code using spaces in StackOverflow...


That's why do...while & while loop was invented.

As requested:

public int getFirstIndexOf(int specifiedNumber) {
    int i = array.Length;
    while(--i > -1 && array[i] != specifiedNumber);

    return i;       
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜