What does return type of ICollection<Person> mean?
I'm looking at开发者_如何学运维 some code samples for Entity Framework 4 and the author created a method that returns ICollection<Person>. I know ICollection is an interface. I know Person is the type of object in the collection. I know I'm getting back a collection of Persons.
The question. Why ICollection? Why not List<>? Why is an interface being used like this? I've used interfaces as "blueprints" for classes, specifying the required members but I don't really understand the usage here.
It's often better to return interfaces instead of concrete classes in public API.
This allows the implementation to change later. For example, it may, in fact, be returning a List<T>
at the moment. However, later, an optimization could be made to return a different type of collection which may have better memory efficiency, allow streaming, or one of many other advantages. As long as that class still implements ICollection<T>
, the implementation is free to switch without causing a breaking API change.
One of the key points of the GoF Design Patterns book is to program to an interface, not to an implementation. The reason for this is the freedom it provides. By returning an interface instead of a specific type, the implementation may more easily be changed in the future without affecting the calling code.
Unless your users wants it from you, your API should expose as little implementation details as possible, and in this case using List<Person>
is implementation detail. For example, if you or your users know that they want to access result set by index, than maybe it better return IList<Person>
instead of ICollection<Person>
, but if you not sure about users scenarios you should expose the most base abstractions as you can (i.e. in this case maybe IEnumerable<Person>
would be enough).
And remember, if lately you decide use more derived return type, it wouldn't break any existing clients, but you can't use more based return type without break some of them.
精彩评论