这标题有点扯。。。
当我编写一个接口(interface)时,通常最好的做法是尽可能返回最具体的接口(interface),还是最少?
例如,假设
interface List2<T> extends List<T>
{
List<T> getRange(int startIndex, int endIndex);
}
改成这样会不会更好
interface List2<T> extends List<T>
{
List2<T> getRange(int startIndex, int endIndex);
}
以便来电者可以调用
getRange
在他们的结果上,同时仍然以多态方式匹配 List?
最佳答案
如果代码变化很大(通常仍在开发中),我会返回最具体的接口(interface),并在进一步需要时使其更广泛。通过这种方式,您可以鼓励不要经常使用界面,并且如果您决定稍后删除或彻底更改界面,则更改内容会更容易。
如果代码是稳定的,或者是要发布的 API 的一部分,我会返回最广泛的接口(interface),以使其对最大的受众可用。
关于oop - 返回接口(interface)时返回更少/更具体的接口(interface)的 OO 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11188543/