@Chamion personal blog

Writing code for humans

Developers read code from left to right, top to bottom. If your intention is to write a function for humans to read, you should write it as a logical progression from start to end.

Three parts of a function

A well-written pure function can be divided into three parts.

  1. Efferent: Parsing and validating inputs.
  2. Transform: Executing some data transformation on the input.
  3. Afferent: Formatting outputs.

Not all three parts are always present but when they are they follow the above order.

Demo time!

Let's take a look at a terrible React component and refactor it to be human readable.

Here's the patient, doc.

const Currency = props => <span>{props.amount.toFixed(2)}{CURRENCY_SYMBOLS[props.currency]}</span>;

This one-liner is hard to read because it has all three parts jumbled together in no sensible order. The efferent part is forked into two property accesses to the props object. The transform part is inlined in the middle, coupled to the efferent parts. The afferent part spans (pun intended) the entire function body.

Let's first extract the efferent part.

const Currency = ({ amount, currency }) => <span>{amount.toFixed(2)}{CURRENCY_SYMBOLS[currency]}</span>;

Now we can at least tell the shape of props at a glance.

Up next, extracting the transform part.

const Currency = ({ amount, currency }) => {     // Efferent
  const symbol = CURRENCY_SYMBOLS[currency];     // Transform
  const formattedAmount = amount.toFixed(2);     // Transform
  return <span>{formattedAmount}{symbol}</span>; // Afferent
};

And we're done!

Next time you review disorderly code you will have the pedantic terms to verbalise your discomfort.