Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO best practice regarding returning less/more specific interface when returning an interface

Tags:

oop

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?

like image 302
Matt G Avatar asked Nov 03 '22 21:11

Matt G


1 Answers

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.

like image 115
S.L. Barth Avatar answered Jan 04 '23 13:01

S.L. Barth