Reputation: 5660
I am extending list in java, but I am not sure of how to deal with exceptions.
class InfiniteList extends ArrayList<Integer> {
InfiniteList(int size) {
super(size);
// if (size < 0) throw new IllegalArgumentException("The size should not be less than zero.");
add(size);
}
Here, I know that as of now, ArrayList constructor throws an exception, if size is negative. My implementation of subclass wants exactly the same behavior. So far world is good.
Now later someone comes and changes ArrayList to accept the negative size and my InfiniteList
fails.
So my solution is to add / duplicate exception handling logic in InfiniteList
. However this comes with issue of code duplication. So I have two options.
Trust the super class ?
Duplicate code ?
What is the common / best practices etc to do here, given that Composition
is not an option.
Upvotes: 1
Views: 52
Reputation: 8009
If you just really can't Compose, and I'm not sure why you can't, I say trust the super class. Especially given that this is a Java API Class that.
Duplicate code is almost always the worst option IMO. The only reason I could see to argue for it in a case similar to this is if the class you are extending a poorly implemented Class and you are trying to hide it's problems to the outside world, or if it throws exceptions that you just really don't want to be coupled to.
Upvotes: 2