Track 04 · Lesson 12 of 15Code that stays easy to change
- 01Principles at a glance
- 02SOLID principles at a glance
- 03S: Single responsibility
- 04O: Open/closed
- 05L: Liskov substitution
- 06I: Interface segregation
- 07D: Dependency inversion
- 08Separation of concerns
- 09DRY: Don't repeat yourself
- 10KISS: Keep it simple
- 11YAGNI: You aren't gonna need it
- 12Composition over configuration
- 13Fail fast
- 14Least surprise
- 15When they disagree
Track 04 · Code that stays easy to change
Composition over configuration
Lesson 12 of 15· 6 min
Build complex pieces by combining small ones, not by configuring one big one.
Build a delete dialog
Then add an illustration
Build a delete dialog
The code you'd write
<ConfirmDialog
open={open}
onOpenChange={setOpen}
showTitle
title="Delete project?"
showDescription
description="This removes all 34 files."
showInput
inputLabel="Type the project name"
showCancel
cancelLabel="Cancel"
showConfirm
confirmLabel="Delete"
confirmVariant="destructive"
/>13 props to learn, and turning things off still means passing them. Try adding an illustration.
type ConfirmDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
showTitle?: boolean;
title?: string;
showDescription?: boolean;
description?: string;
showInput?: boolean;
inputLabel?: string;
showCancel?: boolean;
cancelLabel?: string;
showConfirm?: boolean;
confirmLabel?: string;
confirmVariant?: "default" | "destructive";
// Every new layout request becomes another prop here,
// another if-branch below, and another release.
};
export function ConfirmDialog(props: ConfirmDialogProps) {
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
<DialogContent>
{props.showTitle && <DialogTitle>{props.title}</DialogTitle>}
{props.showDescription && <DialogDescription>{props.description}</DialogDescription>}
{props.showInput && <Input aria-label={props.inputLabel} />}
{/* …and so on for every option */}
</DialogContent>
</Dialog>
);
}Configuration hits a wall#
A configured component can only do what its author predicted. Every new need means a new prop, every prop means a new combination to test (the YAGNI problem again), and eventually someone needs a layout the props can't express at all. Then it's a pull request to the shared package, a review, a release, and a wait.
Composition hands over control#
Composed parts, like Dialog, DialogHeader, DialogTitle and DialogFooter, each do one small job, and the caller arranges them. Need an illustration? Put an img inside. Don't want a description? Don't write one. Nobody had to predict your layout, and nobody has to approve it.
That's the pattern behind most modern component libraries, and it works just as well for your own components: accept children instead of adding another prop.
Check yourself