Object Composition is a fairly common method to explain in very simple terms what Object-Oriented Programming is about. Most developers can probably remember seeing an example in a textbook, blog or class that used the concept of a car to explain composition. In this example, the car is a composite type which contains parts, such as wheels, engine, seats, etc.
This kind of example is fairly simplistic and perhaps unhelpful in a real world project, but the concept of composition can provide benefits to software architecture when combined with other patterns and techniques.
For instance, during the process of building a new website we determine that a logging feature is needed that will allow us to know how long it takes every action on the website to execute. If viewing all new blog posts seems particularly slow, we would then have some data to take a look at to determine what the users were doing and exactly how long the process was taking so improvements could be made. Rather than repeating ourselves by copying and pasting same code, objection composition allows us to write one piece of code that can handle the entire concerns of this feature.
If we combine the code above with some standard dependency injection using our container of choice Simple Injector, we can have every action on the website’s performance recorded via the code above to the file, email or service of our choice without any added work.
Additionally, if a new developer unfamiliar with the structure of the code works on the project, they still have access to the benefits and features of the composed code without needing to add boilerplate code to their own actions.