Object model design: collections on classes
- by Luke Puplett
Hi all,
Consider Train.Passengers, what type would you use for Passengers where passengers are not supposed to be added or removed by the consuming code?
I'm using .NET Framework, so this discussion would suit .NET, but it could apply to a number of modern languages/frameworks.
In the .NET Framework, the List is not supposed to be publicly exposed. There's Collection and ICollection and guidance, which I tend to agree with, is to return the closest concrete type down the inheritance tree, so that'd be Collection since it is already an ICollection.
But Collection has read/write semantics and so possibly it should be a ReadOnlyCollection, but its arguably common sense not to alter the contents of a collection that you don't have intimate knowledge about so is it necessary?
And it requires extra work internally and can be a pain with (de)serialization.
At the extreme ends I could just return Person[] (since LINQ now provides much of the benefits that previously would have been afforded by a more specified collection) or even build a strongly-typed PersonCollection or ReadOnlyPersonCollection!
What do you do?
Thanks for your time.
Luke