Concept
How should a class manage owned collections and avoid shallow copies?
ComputerScienceOne / Composition
"We can take this concept further and design our classes to own collections of other classes. For example, we could define a Course class and then update our Student class to own a collection of Course objects representing a student’s class schedule (this type of collection ownership is sometimes referred to as aggregation rather than strict composition).\n\n1 private Set<Course> schedule;\n\nBoth of these updates beg the question: who is responsible for instantiating the instances of dateOfBirth and the schedule? Should we force the “outside” user of our Student class to build the LocalDate instance and pass it to a constructor? Should we allow the outside code to simply provide us a date of birth as a string? Both of these design choices have advantages and disadvantages that have to be considered.\n\nWhat about the course schedule? We could require that a user provide the constructor with a pre-computed Set of courses, but care must be taken. Consider the following (partial) example.\n\n1 public Student(..., Set<Course> schedule) {\n\n2 ...\n\n3 this.schedule = schedule;\n\n4 }\n\nThis is an example of a shallow copy: the instance’s schedule variable is referencing the same collection as the parameter variable. If a change is made, say a course is added, via one of these references, then the change is effectively made for both. If we are going to design it this way, it would be better to make a deep copy of the set of courses:\n\n1 public Student(..., Set<Course> schedule) {\n\n2 ...\n\n3 this.schedule = new HashSet<Course>(schedule);\n\n4 }\n\nThis is the same pattern we described above: almost every data structure in the Java Collections library has a (deep) copy constructor."
Related Ideas
- How does composition allow objects to own instances of other objects?ComputerScienceOne · Composition
- How can adding an addCourse method make a Student object more flexible?ComputerScienceOne · Example
- What is composition in object-oriented class design?ComputerScienceOne · Common Methods
- What does the completed PHP Student class look like?ComputerScienceOne · Example
- How can you create a deep copy of an integer array in Java?ComputerScienceOne · Multidimensional Arrays
- How do Java sets store unordered unique elements?ComputerScienceOne · Dynamic Data Structures
- How should a copied structure avoid sharing references?ComputerScienceOne · Factory Functions
- How can you create a deep copy of a Student structure?ComputerScienceOne · To String Functions