Domanda

How can I minimize the repeated exception throwing code in the code:

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;
}
È stato utile?

Soluzione

Create a method that will throw an exception:

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

You can then call it:

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;
}

Altri suggerimenti

This is pretty easy to do, but I'd suggest to use an existing method:

 checkElementIndex(index, this.info.length)

from Guava's Preconditions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top