Fl4m3Ph03n1x

Fl4m3Ph03n1x

Functional Architecture in Elixir

Background

I am currently reading Unit Testing Principles, Practices, and Patterns to improve at TDD.

The book has object oriented languages in mind and follows the classical school of TDD, but I overall find value in reading. Many of the patterns and ideas the book has, can after all be brought to Elixir and other non-OOP languages. TDD does not adhere to a specific paradigm after all.

Functional architecure

The book mentions two main types of architectures. Hexagonal Architecture and Functional Architecture. The second one (FA), is considered by the author a subset of HA, an extreme where all the side effects and collaborators are pushed to the service layer, thus keeping the core purely functional and easily testable. In reality, his idea of FA is very compatible with what some people know as Functional core, Imperative shell.

Problems with FA

The author mentions that FA works best when the actions to be taken are in the following order:

  1. Get data from external dependencies
  2. Make decision
  3. Apply decision to ugly outside world

This has a major drawback. In many cases, the decision making process (point 2) can’t be done without querying for more external information, aka, the flow is something like:

  1. Get data from external dependencies
  2. Make decision A
  3. Get more data from external dependencies
  4. Make final decision
  5. Apply decision to ugly outside world

Solution?

They author suggests two possible solutions:

  • Use the CanExecute/Execute pattern
  • Send messages to a queue and have external dependencies read from such queue

In the first one, the external dependency, asks the core if it can perform a given action. If so, it performs it.
In the second one the external dependency reads from a queue of actions it needs to perform.

Opinions!

I personally don’t like the first solution. If I have a controller, for example, this means my controller will be littered with if statements. I want my controllers as dumb as possible.

The second one is more akin to what I believe makes sense using in Elixir. But the book mentions no processes nor mailboxes. Just a simple module that has a list of actions that need to be done, it works with mutable state. I am not really sure how to translate this to Elixir.

What do you guys think? What are your opinions?

Most Liked

sasajuric

sasajuric

Author of Elixir In Action

If I understand this correctly, I think I did something similar in my To spawn, or not to spawn article. It’s a long article, but a tl;dr is that I’m building a Blackjack as a functional abstraction, and then stick an imperative shell around it. So for example, to start a single round, we do:

{instructions, round} = Blackjack.Round.start([:player_1, :player_2])

Where round is the functional data structure representing the state of the round, while instructions is the list of instructions which the shell has to execute. An example content of instructions:

[
  {:notify_player, :player_1, {:deal_card, %{rank: 4, suit: :hearts}}},
  {:notify_player, :player_1, {:deal_card, %{rank: 8, suit: :diamonds}}},
  {:notify_player, :player_1, :move}
]

I should note that I’m not advocating such approach in all the cases. In the blackjack example it felt natural because the steps are simple (invoke functional core, interpret instructions, rinse&repeat), and also because both concerns are complex enough to justify the separation.

If the protocol is more complex, requiring multiple different invocations to the core, intertwined with different imperative instructions, I don’t think it’s worth it. Such separation would obfuscate the flow, and the complexity of the imperative shell would require more exhaustive testing at this level, at which point the tests of the core are likely not needed anymore.

madlep

madlep

I did a talk about exactly that a few weeks ago at RubyConf AU (not Elixir, but it’s mostly translatable).

The code is sort of usable, but more demo code for talking through. I’ve almost got it polished up (with tests etc), and will blog about it in a bit more detail soon.

(TL;DR - you can use free monads as a solution to separate functional core / imperative shell)

If you’ve got a simple “input → pure logic → output” problem, functional core is easy - because it’s just plain old functions. However in the case where you have to go up and down through the shell/core it gets trickier.

The worked example in my talk was code that gets data from an external API, iterates over it, then for each item has to query the DB to decide on action to take - so something that doesn’t fit the simple functional approach, as you’ve got lots of side effects intermingled with business logic.

The approach I showed was turning side effects into values in the functional core to returning. The effect values have enough data to call the side effect, and a function to then call next with the result of the side effect once it is executed by the shell. This way you can build up a recursive functional data structure representing the chain of actions (with iteration/branching etc as required) without actually having to execute any side effects - this makes texting super easy to decouple side effects from your core business logic.

The functional core only builds those values, but doesn’t execute them. The shell then receives them as the return value from calling the core and actually carries them out. As it executes each one, it calls the next function for that action defined in the core. The shell then only has to be a bunch of independent service functions for executing effects and applying them to the effect values.

The shell has zero business logic, but can do side effects, while the core is nothing BUT business logic, and with no code for executing side effects at all.

LostKobrakai

LostKobrakai

Who said that the mutable shell needs to be constraint to only being in the controller? If you want a dump controller (only doing http related stuff) then you can have a module in between your controller and your functional core doing the mutable work.

Where Next?

Popular in Discussions Top

PragTob
Hello everyone, I know we had quite some threads (read through lots of them) about background job processing but it remains a hotly deba...
New
ben-pr-p
In general I’ve been sticking to this community style guide GitHub - christopheradams/elixir_style_guide: A community driven style guide ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39523 209
New
AlexMcConnell
The reason that Rails is as popular as it is is because it’s very easy for relatively inexperienced developers to get a lot of work done....
588 19675 166
New
chulkilee
Here are the list of HTTP client libraries/wrappers, and some thoughts on HTTP client in general. I’d like to hear from others how they w...
New
tomekowal
Hey guys! I want to create a toy project that shows a chart of temperature over time and updates every 5 seconds. I feel LiveView is per...
New
fireproofsocks
This is more of a general question, but I’m wondering how other people in the community think about the pattern matching in function sign...
New
sashaafm
Piggy backing a bit on @dvcrn topic BEAM optimization for functions with static return type?, I’ve been trying to understand in a deeper ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
AstonJ
It’s been a while since we’ve had a thread like this, so what better way to kick off the year with :003: What does being an Elixir user ...
New

Other popular topics Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

We're in Beta

About us Mission Statement