Function and Object Composition

This post is my notes and thoughts on reading Composing Software: An Introduction by Eric elliot.

Software development is the process of taking big problems and breaking them down into increasingly smaller problems. Composition is how you manage and order those Matryoshka dolls in an orderly, neat and understandable fashion.

We will be distinguishing between two types of software design compositions; functional composition and object composition.

Functional Composition

Functional composition is essentially daisy-chaining functions, or piping one functions' output into anothers' input. Promises and decorators are examples of functional composition.

Chaining functions together without explicitly stating function variables is called point-free style. You essentially write a function that returns a new function. This allows us to write small, simple single-responsibility functions that are responsible for only one thing at a time.

One of the benefits of piping functions together is that it's easier to read your code, and to see exactly each function individually. You can focus on one piece at a time and know exactly what's doing, without having to worry about how it might mutate or change things somewhere else.

Another benefit is that testing becomes much simpler - you can test each function individually and reduce the cognitive load of writing test cases, because each function should be responsible for only one piece of testable computation.

Object Composition

And object composition on the other hand is a collection of primitives(strings, integers, booleans, ect). Examples of object compositions are objects, arrays, sets, maps, mixins and class inheritance.

Class inheritance should be avoid when possible though, as it's tight coupling and rigid hierarchy taxonomies makes it less flexible and dynamic.

The book Design Patterns: Elements of Reusable Object-Oriented Software states “Favor object composition over class inheritance”, which means you should only create composites with the exact required components, not all the parents inherited components, like with class inheritance.

There are 3 basic object composition types; delegation(for instance state management), acquaintance (when a composition contains a reference to an external object) and aggregate (objects with child and parent relationships).

Show Comments
Buy me a coffeeBuy me a coffee