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:
- Get data from external dependencies
- Make decision
- 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:
- Get data from external dependencies
- Make decision A
- Get more data from external dependencies
- Make final decision
- 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
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
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
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.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










