Dec 27, 2015
A Bit On OOP
Chances are, if you hear the words “object oriented programming”, this is what you will think of. The tried, true, and boring example of classical inheritance. One class extends another, mostly based around an animal or car of some kind.
So, What Is Object Composition.
Put bluntly, object composition is the coming together of several tiny objects to form a whole under a class that acts as a kind of orchestrator. Take a bicycle for example. A bicycle is made up of many tiny and intricate parts that all have to work together to achieve a single goal, move the rider forward. Some of these parts might include…
- Gear shifting
Now, class extension is great, but only solves a very specific set of problems. Extension is fantastic for creating trees hierarchies of functionality, but it doesn’t really help us with more complex machines. For example, our bicycle’s breaks and wheels may need to be instances of their own classes, and they will need to be able to work together. When you use the breaks, the wheels shouldn’t be allowed to move. Also, forcing the wheels to move while breaks are being used may cause damage to the break system. Something needs to manage this relationship.
When And Where?
Low Level APIs
Libraries like D3 and jQuery, or the JS APIs for canvas, DOM manipulation, and audio are prime candidates for object composition. Anything that includes a wide variety of tiny manipulatable objects works well. For a more practical example, see how we can wrap a basic D3 line graph in an ES6 class.
Because object composition works best with complex mechanisms, it works great with graph libraries like D3. You really do need something to manage all of the objects built around scales, ranges, domains, axis, data, and more. We will make use of a basic ES6 class. Though this is a very very basic example, you can see how our render and path functions don’t really have any complex logic of their own. They just tell the other objects how to do their jobs.
You might be thinking, “this sounds like a controller”. And you would be partially right. Controllers like web components operate really well under this pattern.
When thinking about how to implement your composed objects, you have many options. Though, the best candidate I have seen to date is React, due to how little code it takes to go from plain ES6 classes to working web components. Let’s revisit the previous ES6 only example and see what it would look like as a React Component.