That title's a little tricky... When I'm writing an interface, is it generally best practice to return the most specific interface possible, or least?
For example, suppose
interface List2<T> extends List<T>
{
List<T> getRange(int startIndex, int endIndex);
}
Would it be better to change it to
interface List2<T> extends List<T>
{
List2<T> getRange(int startIndex, int endIndex);
}
so that callers can call getRange
on their result, while still matching List polymorphically?
If the code is changing a lot (usually while still in development), I would return the most specific interface, and make it broader when further needs required it. This way, you encourage that the interface is not used too often, and it's easier to change things if you decide to remove or radically change the interface later.
If the code is stable, or part of an API to be published, I would return the broadest interface, to make it usable to the largest audience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With