pmjoe

pmjoe

Best way to propagate state/dependencies?

I’m having some questions regards state propagation and making the cost testable. The application is structured in a way that the concurrency comes from the HTTP requests, so the webserver will create a new process for each request. Once the request hits my code the code doesn’t have any parallel execution or things like GenServers at all. It’s plain functions calling functions.

And now is the question, imagine that I have 3 layers:

  • handler/http
  • service
  • persistence

The handler calls the service and the service calls the persistence. But to avoid hardcoding the dependencies I need to have some way to pass these values around. My first try was with a centralized state agent, it works but not ideal, I can’t even run parallel tests because they all depend on the same global state agent. My next approach would be to do something like a context that is propagated through all the requests. What do you guys think of this approach?

I should always depend on the services that are passed to my function, so my signature would be something like this:

def send_link(%{user_service: user_service, expiration: expiration}, email) do
end

Instead of this code have a hard dependency on some service, like the user service, it can simply receive it as the first argument.

Wait for some opinions, is this good? should I do something different? Any recommendation of docs to learn more about state management with Elixir?

Most Liked

al2o3cr

al2o3cr

It’s arguable whether dependency injection in this style makes code “more testable”, but it’s not debatable that it makes it much harder for the compiler and other tools. Code like:

user_service.some_function(arg1, arg2)

can’t be checked at compile time for correctness like ActualUserService.some_function(arg1, arg2) can.

I’ve seen this cause failures more than once in applications with strongly-injected “unit tests” that featured mocks that didn’t have the correct signatures. 100% code coverage, all green, 100% broken in production.

Instead of injecting a module for “persistence” into the functions in the “service”, consider approaches like defunctionalization that would instead make the “service” and “persistence” functions that are chained together by the integrating code (in the handler):

# real code should do a lot moar error handling
{:ok, result, commands} = ServiceModule.do_stuff(args)
:ok = Persistence.execute(commands)

Here commands might be a list of tuples like {:update, some_id, new_value} or more structured things like {:insert, %Ecto.Changeset{}}.

This allows each module to be tested cleanly in isolation - the output of ServiceModule.do_stuff can be inspected, pattern-matched, and asserted on in tests without any implementation of Persistence at all.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
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 49522 488
New
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement