简体   繁体   English

不适用于接口实现的方法:抛出异常或静默忽略?

[英]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 (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. 例如,如果“List”实现不支持“remove”,则应抛出异常以指示此行为已丢失,因为客户端依赖于预期结果。

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. 绝对会抛出UnsupportedOperationException 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. UnsupportedOperationException更好。 Otherwise client code cannot distinguish the method is availble or not. 否则客户端代码无法区分该方法是否可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM