虽然上面的例子可能表明出现了问题,但NotImplementedException本身始终没有错。这完全是关于超类的合同以及实施这个合同的子类。如果你的超类有这样的方法
// This method is optional and may be not supported
// If not supported it should throw NotImplementedException
// To find out if it is supported or not, use isAddItemSupported()
public void AddItem(double a, int b){...}
然后,不支持这种方法仍然可以与合同。如果不支持,您可能应该禁用UI中的相应操作。所以如果你对这样的合约可以,那么子类就可以正确地实现它。
当客户明确声明,它不使用所有类的方法,并永远不会另一种选择。像这样
// This method never modifies orders, it just iterates over
// them and gets elements by index.
// We decided to be not very bureaucratic and not define ReadonlyList interface,
// and this is closed-source 3rd party library so you can not modify it yourself.
// ha-ha-ha
public void saveOrders(List<Order> orders){...}
然后可以通过不支持添加,删除和其他增变器的List实现。只需记录它。
// Use with care - this implementation does not implement entire List contract
// It does not support methods that modify the content of the list.
public ReadonlyListImpl implements List{...}
虽然有你的代码来定义所有的合同是好的,因为它让你的编译器检查,如果你违反了合同,有时是不合理的,你必须诉诸弱定义的合同,这样的评论。
总而言之一句话说到这个问题,如果你真的可以放心地使用你的子类的父类,考虑到超类是由它的合同,不仅是代码中定义。
我不知道NotImplementedException是否是一种代码异味 - 异常表明它没有实现_yet_。如果它是一个NotSupportedException,我同意。 – Lennaert 2009-04-09 06:59:42
同意。考虑到我的懒惰 - 我只是复制并粘贴了原来的问题。 – LeopardSkinPillBoxHat 2009-04-09 07:07:53
我修改了我对NotSupportedException的回答。 – LeopardSkinPillBoxHat 2009-04-09 07:21:57