Initialize a collection within an object?

后端 未结 10 1250
长发绾君心
长发绾君心 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:38

    I prefer to create the collection upon instantiation, provide add/remove methods in the containing object, and if needed, provide addAll/removeAll methods for adding and removing entire external collections. I never allow the collection object to be accessed for get or set by the caller - I may, however, provide a getter that returns a copy (poss. immutable) of the collection.

    I have also had copy-on-write implementations which provide an immutably wrapped view, since any mutation will create a new underlying collection.

    0 讨论(0)
  • 2021-02-04 15:41

    I create an empty collection. Sure, it has a slight memory cost, but not a large enough one to be concerned about it.

    0 讨论(0)
  • 2021-02-04 15:41

    As a general rule, I think the object should create the collection and provide methods for manipulating it; add/get/remove. When following this rule, you should not provide methods for setting the collection directly. If you want a method like setSomeCollection(Collection someCollection) for convenience, the implementation of this method should not set the reference within the object, but copy the values from the method parameter collection to the collection within the object;

    public void setSomeCollection(Collection someCollection) {
       this.someCollection.clear();
       this.someCollection.addAll(someCollection);
    }
    

    You should do this, so clients of your API cannot get access to the collection that your class maintains. If they do, they can manipulate it without using objects of your class and violate constraints that your class guarantees.

    The same is true if providing a getter; you should either return a copy of your internal colleciton, or a read-only version of it. Apache commons-collections and google-collections provide methods for creating immutable wrappers around a collection, aswell as the ones that come with Java in the java.util package; java.util.Collections.unmodifiable*.

    0 讨论(0)
  • 2021-02-04 15:42

    I typically will create the collection then provide methods to add / remove items from the internal collection rather than making the consumer of the class worry about checking for null. This also gives you the ability to control better what happens to the collection. Ultimately it depends on what it is for, but most likely if your class has a collection it isn't just so that the consumer of the class can have a collection of those objects. Otherwise, why would they use your class?

    0 讨论(0)
提交回复
热议问题