Bifalgorithm post · Computer science one · Composition
How should a class manage owned collections and avoid shallow copies?
How should a class manage owned collections and avoid shallow copies? (Computer science one · Composition) — "We can take this concept further and design our c…
Ideas in this flowchart
- Designing classes that own collections of other classes
- A class can own a collection of instances of another class.
- A Student can own a Set<Course> representing the student's class schedule; this is aggregation rather than strict composition.
- The design must determine who instantiates the dateOfBirth value.
- The outside user can construct a LocalDate and pass it to the Student constructor.
- The outside code can provide the date of birth as a string.
- Both dateOfBirth designs have advantages and disadvantages that require consideration.
- A Student constructor may receive a pre-computed Set<Course> for the schedule.
- Assigning this.schedule = schedule creates a shallow copy because both variables reference the same collection.
- A course added through either reference changes the same underlying schedule.
- The schedule should instead be copied into a separate collection.
- The constructor can use new HashSet<Course>(schedule) to create the copied set.
- This follows the reusable copy-constructor pattern found throughout the Java Collections library.