https://enterprisecraftsmanship.com/posts/return-the-most-specific-type/
In this concrete example, it makes sense to return an Employee object. The Employee class might introduce some functionality specific to employees so it is a good idea to enable the client code to work with it. Changing the return value type to a more generic one puts too many restrictions to the method consumers. In the worst case, the client code would need to manually cast the Person object to an Employee, so it is better to not make them do that.
Of course, it’s not always possible to use generic types for input parameters. Otherwise, we would always use Object as the type of the method parameters. That brings us to the second part of the guideline: make your methods accept parameters of the most generic types possible.
Okay, but why bother? Why do we need to follow these guidelines? It turns out, there’s some higher level reason behind these rules. That is, you should always try to make it easier for the clients of your code to use your API, even if the client is you. Good software design is all about simplicity. The simpler and easier you make it, the better.
- If you develop an in-house software, do use the specific type for return values and the most generic type for input parameters even in case of collections.
- If a method is a part of a redistributable library’s public API, use interfaces instead of concrete collection types to introduce both return values and input parameters.
- If a method returns a read-only collection, show that by using IReadOnlyList or IReadOnlyCollection as the return value type.
It means that you should always prefer interfaces over concrete collection types for methods that are parts of a redistributable library’s public API. This statement is true for both returning value and input parameter types.