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.
AddItem()
andRemoveItem()
work, if they don't have any parameters?