开发者

Methods not applicable for the implementation of an interface: throw Exception or ignore silently?

I'm currently implementing a rather large interface and some of its methods are not applicable to the implementation.

Should I do something akin to:

/**
 * @throws UnsupportedOperationException always. This method is not applicable.
 */
public void fooMethod() {
  throw new UnsupportedOperationException("This method is not applicable for this implementation.");
}

or just silently ignore it, doing nothing:

public void fooMethod() {
}

The former way would alert a user of the class that it doesn't do a portion of what the interface provides, but might perhaps clash with legacy code where the class is used as a drop-in replacement 开发者_如何学Python(which it isn't, though).

Is there a general rule regarding this?


I think that simply depends on the contract defined by the method.

If for example "remove" is not supported by your "List" implementation, you should throw an exception to indicate that this behavior is missing because the client relies on an expected result.

If the feature is optional in the sense that the contract says for example "this method should inform the user about an ongoing activity" you're free to make a dummy implementation.


Throw an UnsupportedOperationException, definitely. I can't see any benefit in failing silently, unless the method is meant to be a "hint" sort of method.

If you can refactor your interface and split it up a bit, that would probably be cleaner - but I understand that with a legacy codebase this may not be feasible.


UnsupportedOperationException is better. Otherwise client code cannot distinguish the method is availble or not.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜