Composition of Classes

Composition-GUI
Composition GUI

A golden rule in coding is the modularization: the bigger your project is, the more difficult it's to keep it in a mono structure. You're naturally brought to separate logically and even in different files the code portions which are separable.

When you start to design your software in the OOP vision you surely must face these situations, in a different way: to get order inside an initial nebulous idea it's so important to recognize the who/what!

Easy to say, but only the practice and a good eyes can help you: in a big series of data your job is to assign roles and hierarchies, connections and relationships. In facts, as we said in the OOP introduction, over the who/what boxes there are the intercommunications, which are essential parts of them.

Here we show one kind, the so called composition.

Generally a composition means a concurrence of factors bound one each other, whose result is given by the factors themselves and the proportions they express: a typical example is a music composition.
In some contexts a composition defines the manner in which something is composed; not the result but the process behind.
Every meaning you find it includes the concept of relationship between two "actors", at least.

This is the point: which kind of hierarchy does the composition imply?

We'll explain it by keeping on with our employee example, expanding it a little bit.

An employee brings an amount of informations to manage: we saw naturally the name, the surname, and the number ID (hypothetically for the bureau's needs).
Anything else? what if he/she has some documents? just in case the boss wants to check if the employee is honest or not.

Well... nothing difficult! Just put the document properties inside the employee class.
It's a possibility: how much good? not so.

While the idea of a name is implicit with the person, or the ID with the employee; the same has no worth for a document, because this doesn't make the difference (even if worldwide bureaucracy says the opposite!).
If this is true, why don't we try to separate this, always in the OOP approach? is "the document" manageable as a box apart?
Luckily yes; let's see why.

A document is a generic container for more types: we have the passport, the driving license, identity card - in some countries -; plus other possible documents more or less important for the life of people.
We're saying that a document is possibly a class, which every of its main features. That's good!