Object model design: collections on classes

Posted by Luke Puplett on Programmers See other posts from Programmers or by Luke Puplett
Published on 2011-01-07T13:57:18Z Indexed on 2011/01/07 13:59 UTC
Read the original article Hit count: 536

Filed under:
|

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

© Programmers or respective owner

Related posts about design

Related posts about object-oriented