Implementing Composition
Implementing Composition
Yesterday we discovered the similarities and differences between Aggregation and Composition; two types of parent/child relationship competing with Object-Oriented (OO) Inheritance.
Today we’ll take a look at how we implement Composition in code. To recap, in Composition, the child only makes sense when it is part of the parent – it cannot exist independently from the parent.
Yesterday’s example was that of a petrol engine and its component pistons. Pistons are not of much use by themselves. They become useful inside an internal combustion engine. Hence, Composition is a suitable approach to model classes PetrolEngine
and Piston
.
Here is the code for PetrolEngine
again:
public class PetrolEngine { private IList<Piston> Pistons { get; } = new List<Piston>(); public Course(int numberOfPistons = 4) { for (var i = 0; i < numberOfPistons; i++) Pistons.Add(new Piston()); } }
Note that we instantiate the Pistons
inside the constructor – Pistons
are not created outside and then passed as parameters. If we did that, Pistons
could exist by themselves in contravention of the ideas of Composition.
Is there a way in which we can structure our code so that we get a compilation error if we were to reference Piston
outside of PetrolEngine
? I.e. if we constructed Piston
outside of PetrolEngine
or return Piston
from a PetrolEngine
method?
I left you with this question last time.
One person got the answer: Well done, Steve Denman from Safe365!
Steve pointed out that Piston
could be a private, nested class to PetrolEngine
:
public class PetrolEngine { private IList<Piston> Pistons { get; } = new List<Piston>(); public Course(int numberOfPistons = 4) { for (var i = 0; i < numberOfPistons; i++) Pistons.Add(new Piston()); } private class Piston { // Modelling piston behaviour. } }
A few notes:
- We defined class
Piston
asprivate
and inside the definition ofPetrolEngine
. Piston
is not visible outside ofPetrolEngine
. If we try to referencePiston
outsidePetrolEngine
, we will get a compilation error.- Class
Piston
will contribute to the behaviour of its parent class. That makes intuitive sense: Code that does not have an effect is quite useless. Piston
is a private helper class. It partitions behaviour inPetrolEngine
in a way we would otherwise write procedurally. Private classes likePiston
model behaviour consistent with OO.
Next time we’ll take a closer look at Aggregation and its implementation.
Leave a Reply
Want to join the discussion?Feel free to contribute!