1

如何最小化代码中重复的异常抛出代码:

public R get(int index) throws IndexException {
  if (!((0 <= index) && (index < this.info.length))) {
    throw new IndexException();
  }
  return this.info[index];
}

public void set(int index, R r) throws IndexException {
  if (!((0 <= index) && (index < this.info.length))) {
    throw new IndexException();
  }
  this.info[index] = r;
}
4

2 回答 2

5

创建一个会抛出异常的方法:

private void checkBounds(int index) throws IndexException {
  if (index < 0 || index >= info.length) {
     throw new IndexException();
  }
}

然后你可以调用它:

public R get(int index) throws IndexException {
  checkBounds(index);
  return this.info[index];
}

public void set(int index, R r) throws IndexException {
  checkBounds(index);
  this.info[index] = r;
}
于 2014-02-12T00:50:24.590 回答
1

这很容易做到,但我建议使用现有的方法:

 checkElementIndex(index, this.info.length)

来自番石榴的前提条件

于 2014-02-12T01:26:46.943 回答