tezvyn:

Component Composition: Treat a Group Like an Individual

AI-drafted, machine-checkedSource: Wikipedia: Composite patternbeginner

Component composition treats a group of objects the same as a single one. This allows building complex UIs by nesting simple components, like putting a Button inside a Form. The footgun is creating monolithic components instead of small, reusable ones.

WHY IT EXISTS To manage complexity in systems with part-whole hierarchies. Without a uniform way to handle objects, code must constantly check if it's dealing with a single item or a collection of items. This leads to repetitive conditional logic, making the system brittle and hard to extend.

THE MENTAL MODEL Think of it like Russian nesting dolls. Each doll is an object you can interact with. But some dolls are also containers for other dolls. Composition lets you treat any doll the same way, whether it's a simple, solid one (a leaf) or one that contains a whole set (a composite). You can tell any doll to "display itself" without needing to know if it has others inside.

HOW IT WORKS Both individual objects (leaves) and container objects (composites) implement a shared interface. For example, in a UI system, both a simple Button and a complex Card (which contains a button, an image, and text) would have a render() method. When a client calls render() on a component, it doesn't care what kind it is. A Button just renders itself. A Card renders its own wrapper and then calls render() on each of its children in sequence. This recursive structure allows for building arbitrarily complex trees.

WHEN TO USE IT Use this pattern whenever you need to represent a part-whole hierarchy and want to treat all objects in that hierarchy uniformly. This is fundamental to modern UI frameworks (React, Vue, Flutter), graphics engines (a scene is a tree of models, meshes, and lights), and file systems (a directory is a composite that holds files and other directories).

WHEN NOT TO USE IT Avoid this pattern if your object hierarchy is simple and not expected to change, as the abstraction can add unnecessary overhead. It can also make the system overly general; sometimes you want to enforce that a specific composite can only contain certain types of children, which requires adding extra checks.

ONE CANONICAL EXAMPLE In a UI library, you might have a Button component (a leaf) and a Form component (a composite). Both would descend from a base Component class and have a render() method. The Form's render() method would first draw its own container, then loop through its list of child components—like Input fields and the Button—and call render() on each one. The code that uses the Form simply adds children to it and tells the Form to render, trusting composition to handle the rest.

Read the original → en.wikipedia.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.