Legos are snap-together plastic toy parts which children love. They seem to enjoy the snapping part where they can join and build whatever they want.
We as coders love to snap together functional parts, it allows us to build things faster and stronger.
Consider this code:
function components(rpa: RelatedPeopleAddComponent) {
let personComponent = rpa.rpc.personComponent;
let relatedPersonSelectComponent = rpa.rpc.rps;
let relatedPersonGridComponent = rpa.rpg;
let relatedPersonMainComponent = rpa.rpm;
let relatedPersonComponent = rpa.rpc;
return {
pc: personComponent,
sc: relatedPersonSelectComponent,
rpg: relatedPersonGridComponent,
rpm: relatedPersonMainComponent,
rpc: relatedPersonComponent,
};
}
It infers rich composition, as we see plenty of "." (dots). We are able to pull out five different components (and hundreds of properties or functions) from just one parameter passed in. Our return statement allows us to shorten the name for ease of use.
Connecting Lego-like parts
export async function
funcAddToGrid(
rpa: RelatedPeopleAddComponent
) {
// Get addressibility to part components
let { pc, sc, rpg } = components(rpa);
// start joining things together
rpa.relatedPerson = pc.person;
//Build small part for later
let relationKind = sc.currentKind;
// Build small part for later
let relation =
new Relation(
// Each of these are small parts
// from other components.
rpa.person,
rpa.relatedPerson,
// Use Small part
relationKind.id
);
// Build another part
let dspRel = new DisplayableRelation(
rpa.person,
rpa.relatedPerson,
rpa.relationShipKinds,
// Use small part from above
relation
);
// Set value from small part
dspRel.optionToSelect = relationKind.display;
// Set value via composition
dspRel.relationship = pc.person.kind;
// Use 2nd part, adding to grid for Display
rpg.addRelatedPerson(dspRel);
}
We are easily able to reach into our box of components and start building at will. If we are missing any parts, we just add them following the Single Responsibility Principle.
SUMMARY
Anytime we see a '.' (dot) think of composition. Composition allows us to morph an object into predefined types. They may be any of Typescript'intrinsic types. Which could be simple or complex properties or other objects. This is sometimes referred to as Hotizontal Inheritance. It is the realization of 'Favor Composition Over Inheritance'