Take for example the following:
public interface IManager
{
void AddItem(CollectionItem item);
void RemoveItem(CollectionItem item);
}
public interface IManagerCustomCollection
{
ManagerCollection Systems;
}
Is it usually more preferable to create a collection, and allow the consumer to operate directly on the collection?
2
Is it usually more preferable to create a collection, and allow the consumer to operate directly on the collection?
It depends. Do you expect your user to create, manipulate, and otherwise use the collection? Or do you want to let them to do a few collection-like operations on something… that’s not really a collection?
But before you answer: consider that this is a code smell. Well, it’s two possible code smells:
- You’re making your own collection type. – The standard library collections (and interfaces) are good, extensive, and everyone knows them. Be really sure you need to before making a new one.
- You’re maybe violating single responsibility. – If you have some thing, and then that thing also has
Add
,Remove
, etc… your thing might be doing two things. Look to separate those responsibilities.
All that said, I tend to prefer option 1. It provides stronger control over whatever weird invariants you need to protect if you’re not just using a List
(or whatever other basic collection). Usually these sort of things need to associate the collection with some other instance, which gets hairy if you decouple the collection from its paired instance.
1
I would prefer to expose the API to the collection, that way when you are doing testing you don’t need to worry about constructing the proper collection and you could also do tests where the collection is null etc.
You would also be able to implement your own conditions on which type of items get added to the collection, i.e. no duplicates etc.
Expose access to the collection using an interface, such as IList<T>
, ICollection<T>
or ISet<T>
. Developers are familiar with these interfaces while not tying it to a specific implementation. Throw a NotImplementedException
for methods or properties you do not want to implement.
You lose some functionality. For example, as Jon Skeet points out, the interfaces are subsets of the features offered by concrete classes – IList<T>
has fewer methods and properties than List<T>
, for example. However, LINQ and similar mechanisms still work, unlike implementing your own interfaces or classes.