Circle of purity & Ring of impurity

arun
2 min readApr 4, 2018

--

I heard the terminology “Circle of purity & Ring of impurity” from Venkat S in one of our Java user group meetups. A similar phrase was also mentioned by Gary Bernhardt in his screencast series Destroy all software called “Functional core & Imperative shell”.

The basic idea here is that your code is modularized in such way that the core of it is composed of lot of pure functions and these pure functions are wrapped around by layer of impure functions, which may be interacting with database or network or IO etc. The core is all pure, no mutations and should be very easy to test.

I am really fascinated by this idea and have been experimenting in my own limited ways to achieve it.

Hear me out on one of the refactoring exercises I did recently to achieve this goal.

I have a piece of code, which is run as part of kickstart of a project. The requirement here is that before kickstart I want to validate if the tasks in the project are valid based on certain set of rules. If there are some validation errors, I want to log the error per task and stop the kickstart, else I can return an all good green signal to the calling code to go ahead and perform the Kickstart.

Here is where it started

As you can see the validate function here is doing two things (a) validation and (b) error handling and logging of the errors. Validate is definitely not a pure function and it does mutation operations via the save. And the core piece of our logic in this class which is validation is not so easy to test as it has dependency on error handler.

To make this function more testable, pure and separate out concerns I refactored the code like this

Here I have moved out error handling part out of the validator. Validator is responsible only for validation sticking to SRP.

We have validateTasks as a pure function, metamorphosing to the functional core of our program. It accepts a bunch of tasks and a set of validators to run against each task. It’s output is going to remain same for the given the same set of inputs.

KickstartValidator class becomes the shell which invokes the pure function and get things done. It is now relieved of the error handling part and that responsibility has been delegated to the calling code.

This style mixes OO and functional style of programming and makes code easy to test and maintain.

--

--

arun
arun

Written by arun

I enjoy photography, jungle safari, travel, programming and writing. I'm here to share my experiences.

Responses (1)