java - When should I return the Interface and when the concrete class? -


when programming in java practically always, out of habit, write this:

public list<string> foo() {     return new arraylist<string>(); } 

most of time without thinking it. now, question is: should always specify interface return type? or advisable use actual implementation of interface, , if so, under circumstances?

it obvious using interface has lot of advantages (that's why it's there). in cases doesn't matter concrete implementation used library function. maybe there cases matter. instance, if know access data in list randomly, linkedlist bad. if library function returns interface, don't know. on safe side might need copy list explicitly on arraylist:

list bar = foo(); list mylist = bar instanceof linkedlist ? new arraylist(bar) : bar; 

but seems horrible , coworkers lynch me in cafeteria. , rightfully so.

what guys think? guidelines, when tend towards abstract solution, , when reveal details of implementation potential performance gains?

for instance, if know access data in list randomly, linkedlist bad. if library function returns interface, don't know. on safe side might need copy list explicitly on arraylist.

as else has mentioned, mustn't care how library has implemented functionality, reduce coupling , increasing maintainability of library.

if you, library client, can demonstrate implementation performing badly use case, can contact person in charge , discuss best path follow (a new method case or changing implementation).

that said, example reeks of premature optimization.

if method or can critical, might mention implementation details in documentation.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -