Alex Rivera | Logout

Initialize a collection within an object?

Asked 2008-12-08T19:04:10.770
9

If an object has a property that is a collection, should the object create the collection object or make a consumer check for null? I know the consumer should not assume, just wondering if most people create the collection object if it is never added to.

Edit
Report

1 Answer

3

This depends on the contract you have between your API and the user.

Personally, I like a contract that makes the Object manage its collections, i.e., instantiating them on creation, and ensuring that they can't be set to null via a setter - possibly by providing methods to manage the collection rather than setting the collection itself.

i.e., addFoo(Foo toAdd) instead of setFooSet(Set set), and so on.

But it's up to you.

answered 2008-12-08T19:08:56.767

Your Answer