Disclaimer
Please don't just vote to close this because the title looks subjective, and if it's been asked before please point me to the previous question in the comments and I'll delete this one -- I really did look high and low trying to find a previous question on the subject.
Background
Given I have the following interface and concrete implementation:
public interface IFoo
{
// Some stuff
}
public class Foo : IFoo
{
// Concrete implementations of stuff
}
And somewhere I have the following method:
public Foo GiveMeAFoo()
{
return new Foo();
}
I have traditionally always returned Foo
, seeing as it is inherently an IFoo
anyway, so it can be consumed at the other end as an IFoo
:
IFoo foo = GiveMeAFoo();
The main advantage of this that I can see is that if I really need to consume Foo
somewhere as the concrete implementation, I can.
Actual Question
I recently came across some comments on another question, giving someone a hard time for doing this, suggesting the return type should be IFoo
.
Am I wrong or are they? Can anyone give me a reason why returning the concrete implementation is a bad idea?
I know that it makes sense to require an IFoo
when receiving a parameter to a method, because the less specific a parameter is, the more useful a method is, but surely making the return type specific is unreasonably restrictive.
Edit
The use of IFoo and Foo might have been too vague. Here's a specific example from .NET (in .NET, arrays implement IEnumerable -- i.e. string[] : IEnumerable<string>
)
public string[] GetMeSomeStrings()
{
return new string[] { "first", "second", "third" };
}
Surely it's a bad idea to return IEnumerable here? To get the length property you'd now have to call Enumerable.Count(). I'm not sure about how much is optimised in the background here, but logic would suggest that it's now going to have to count the items by enumerating them, which has got to be bad for performance. If I just return the array as an array, then it's a straight property lookup.