Pure Function vs. Total Function

A pure function:

const add = (a, b) => a + b

vs. a total function:

const addNumbers = (a, b) =>
( isNumber(a) && isNumber(b) )
? {ok: true, data: a + b}
: {ok: false, error: new Error(Either a or b aren't Numbers.)}

While same input, same output, no side effects sounds like the end all, be all… it’s not.

A pure function like this will always return 3:

console.log(add(1, 2))

… but this will always return “1Error: moo”:

console.log(add(1, new Error('moo')))

Not helpful.

This is where types help, no doubt, but at runtime, validation of your your data becomes important when you’re veer away from what types can help you find (range of a number, shape of data from remote JSON, etc).

Using the total function:

console.log(addNumbers(1, 2))

will always give return:

{ok: true, data: 3}

however, if the types aren’t correct:

console.log(addNumbers(1, new Error('moo')))

will always return:

{ok: false, error: {…}}

A much more useful result to the developer, and less burden on their part.

Not all functions need be total. Just make your privates pure, and your publics total, for example. That way the privates don’t get bad data.

Leave a Reply

Your email address will not be published. Required fields are marked *