Concept

What is composition in object-oriented class design?

ComputerScienceOne / Common Methods

"Another important concept when designing classes is composition. Composition is a mechanism by which an object is made up of other objects. One object is said to “own” an instance of another object. To illustrate the importance of composition, we could extend the design of our Student class to include a date of birth. However, a date of birth is also made up of multiple pieces of data (a year, a month, a date, and maybe even a time and/or locale). We could design our own date/time class to model this, but its generally best to use what the language already provides. PHP 5.2 introduced the DateTime object in which there is a lot of functionality supporting the representation and comparison of dates and time. We can take this concept further and have our own user-defined classes own instances of each other. 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 composition). Both of these design 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 a DateTime instance and pass it to a constructor? Should we allow the outside code to simply provide us a date of birth as a string and make the constructor responsible for creating the proper DateTime instance? Do we require that a user create a complete array of Course instances and provide it to the constructor at instantiation?"

Related Ideas

What is composition in object-oriented class design? | ComputerScienceOne | Bifalgorithm | Bifalgorithm