Member-only story

Pure functions are easier to test

Alonso Del Arte
4 min readNov 15, 2024

--

Photo by sheri silver on Unsplash

Beginning Java programmers often wind up writing a main() procedure running dozens or even hundreds of lines. Clearly that’s difficult to test. Short functions are much easier to test, and short pure functions are even easier to test.

A pure function is simply a function that depends only on its parameters for its result.

For example, Math.abs(). Its results depends strictly only on its parameter.

A function is not pure if its result depends on anything besides its parameters.

For example, Math.random(), which depends on, among other things, how many calls have been made before.

Pure functions are easier to test, especially when the number of possible parameter combinations is small. There is no state to set up or mock for the tests.

The Java Development Kit (JDK) as a whole has been moving away from functions that depend on state for their results.

Consider for example the toString() overrides in java.util.Currency and java.time.LocalDate. The former has been available since Java 1.4, the latter since Java 8.

Actually, those are both pure functions. Given a Currency instance, the toString() function always returns the 3-letter ISO-4217 code for that currency. For example, the toString() for the Currency

--

--

Alonso Del Arte
Alonso Del Arte

Written by Alonso Del Arte

is a Java and Scala developer from Detroit, Michigan. AWS Cloud Practitioner Foundational certified

No responses yet