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 に答える