Skip to content

Lesson 3 of 9 · 21m

Composition Over Utility Soup

Compose small functions into readable pipelines, choose argument order deliberately, and avoid helper abstractions that obscure data flow.

Most JavaScript codebases do not fail because they lack abstractions. They fail because every abstraction is different: one helper mutates, one returns a wrapper, one hides an error, one takes data first and another takes it last. Composition is the discipline of making small functions fit together with predictable shapes.

Start with transformations, not cleverness

const normalize = (email) => email.trim().toLowerCase();
const looksLikeEmail = (email) => email.includes("@") && email.includes(".");
const toUserInput = (email) => ({ email, marketing: false });

function parseSignup(raw) {
  const email = normalize(raw);
  if (!looksLikeEmail(email)) throw new Error("invalid email");
  return toUserInput(email);
}

This is composition in the plainest sense: output of one function becomes input to the next. No library is required. Intermediate names are often clearer than a generalized pipeline helper.

Pipelines should read in execution order

// nested calls make the first operation hardest to see
const result = format(sort(filter(rows, active), byName), asTable);

// named steps expose the data flow
const activeRows = filter(rows, active);
const sortedRows = sort(activeRows, byName);
const table = format(sortedRows, asTable);

Array method chains are already pipelines: rows.filter(active).map(toRow).slice(0, 20). Reach for pipe only when the chain no longer fits the medium.

Data-last order enables reuse

const take = (count) => (items) => items.slice(0, count);
const where = (predicate) => (items) => items.filter(predicate);

const firstFiveActive = take(5);
const activeOnly = where((item) => item.active);

Configuration first and data last lets the same configured operation travel across collections. That style is useful when reused; it is noise when used once. Do not contort application code so a library demo looks elegant.

Utility soup is the failure mode

helpers.js, misc.js, and utils2.js usually mean extraction happened before the contract was understood. Good primitives have stable shapes: a predicate is a -> boolean, a mapper is a -> b, a reducer combines values. If a helper needs a paragraph to explain its inputs, it is not a composable primitive.

Field notes

  • Good intermediate names are documentation, not wasted lines.
  • Once one step returns a promise, the whole pipeline is asynchronous and error behavior changes. Say so in the function name or type.
  • Extract functions when the contract is stable, not when a line is long.
  • The best composition often looks unimpressive: small functions, clear names, no framework.

Was this lesson helpful?

Sign in to rate