An experience refactoring real world Elixir code

Rafa Noronha
Noronha dot tech
Published in
2 min readDec 22, 2021

I had the opportunity to rant about my take on hexagonal architecture with Elixir.
And today I want to share this experience refactoring a piece of business logic code around exactly the same context / landscape: Elixir code-base, functional programming, microservice architecture, hexagonal architecture / Ports and Adapters design pattern.

Ports and Adapters

The following is a decent approximation of our microservice.

+----------+--------------------------+--------------------+
| http | pubsub events | queue jobs | db | 3rd party apis
|----------+--------------------------+--------------------+
| domain
|----------------------------------------------------------+

Http endpoints, pubsub events and queue jobs are the primary adapters driving the capabilities of the application. Database and 3rd party (rest) apis are the main secondary adapters our application drives.

In a nutshell, primary adapters are kind of entry-points to all your application’s use cases. Secondary adapters are sort of bridges to any external stuff your application drives in order to achieve its use cases.

Now you went through all that introduction you deserve some Elixir beauty. So these are two version of the same module, same functionality.
Keep in mind that I decided to replace actual business nouns with foobars and lorem ipsums.

First version, is prior the refactoring:

Second version, refactored out:

WOW!

First things first. That first version really had some smell.
And the second version, it’s doing way less stuff.

Turns out the second version doing way less stuff is exactly what we are looking for.
Elixir and other functional languages can really leverage expressiveness from the source code. And I’m aiming exactly for this kind of expressiveness in my business logic code when I bet in Ports and Adapters.

Speaking in adapters, you gotta pull some work from them. They live in the boundaries of the application and have the opportunity to protect the domain from any foreign abstraction leak.
Stuff leaking from outside world (pubsub events) directly into the microservice domain is exactly what was going on with this refactoring opportunity.

--

--

Rafa Noronha
Noronha dot tech

Construindo produtos digitais desde antes da bolha tech