Initialize a collection within an object?

后端 未结 10 1352
长发绾君心
长发绾君心 2021-02-04 15:03

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

10条回答
  •  耶瑟儿~
    2021-02-04 15:35

    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.

提交回复
热议问题