1

In chapter 24 of Code Complete the author says, in reference to encapsulate downcasting when returning from a method, "If a routine returns an object, it normally should return the most specific type of object it knows about. This is particurlarly applicable to routines that return iterators, collections, elements of collections, and so on."

Now, being a C# programmer, I typically always return ICollection instead of, say, IList or even List. By using an interface from higher up in the hierarchy I am free to switch collection type in the method without breaking the method interface. This seems like a good thing. What am I missing?

1 Answer 1

2

This a question of weighing the benefits to yourself, the library author, and the benefits to others, the application programmers.

Publishing a general type leaves you free to change your mind later without violating the contract, but at the same time, it devalues the contract itself. If you return a generic collection, your user can't do anything with it except enumerate it. If that's all that is needed, fine. But if the user actually needs a well-defined ordering of the returned elements, a Collection is not sufficient. In a perfect world, every application programmer would recognize this and refrain from depending on the order in which the elements are returned. However (you know where this is going...), in the real world, what will likely happen is that you declare your results as a Collection, but implement them via some kind of List, and your users observe a predictable order of elements and come to depend on it. Then when you change the implementation, their programs break and they curse you. If you had committed to generating a List in the first place, this can't happen.

This is why it's a good idea to commit at least to some level of specific data structure in public interfaces. It is actually quite rare that you change your mind about whether a data structure will allow duplicates, or whether it allows null, or whether it has to be ordered or not, so decisions such as choosing List over Set aren't that hard to make, and they give your users more assurances to work with (rather than falsely assuming things that are true now but might change without notice).

1
  • 1
    Makes sense. And I guess the arguments hold for using IList instead of LinkedList/List etc. I cannot recall a time when I actually changed the implementation in a method after it had been committed. Thanks. Commented Jul 23, 2013 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.