jTy

jTy

Dependency injection & design by interface / SMI

Hi there! I’ve been playing with Elixir for a while and stumbled upon dependency injection. The topic comes naturally to me as having C# background where it’s pretty-well known, especially amongst professionals. Since we are dealing with callbacks and behaviors instead of abstraction and implementation while there is no such concept as an interface (which by the way, I consider if occurred, would probably be somewhere between protocol and behavior in terms of both complexity and (supposedly) ergonomics), I find it as cumbersome - an obstacle that effectively stops me from considering Elixir at production whether it is small or medium-size project., not even mentioning larger ones.
Some people pointed me to libraries that concentrate on facilitating tests (in particular test doubles - mocks) although dependency injection has nothing to do with that (admittedly we can bring them together under certain circumstances). I would love to write beautiful, cohesive, loosely-coupled programs - just not sure if that is currently possible.

I thought that maybe I can utilize what’s already existing and achieve what I want with metaprogramming - for demonstration let’s consider the following example:

  1. We start with an interface:
    i_writer.ex
defmodule IWriter do
  @callback write() :: atom()
  @callback write(args :: any()) :: atom()
  @optional_callbacks write: 0, write: 1
  defmacro __using__(_) do
    quote location: :keep do
      @behaviour IWriter
      @after_compile IWriter

      defp do_write(), do: IWriter.do_write(__MODULE__)
      defp do_write(write_args), do: IWriter.do_write(__MODULE__, write_args)
    end
  end

  def do_write(module),
    do: fn -> apply(module, :write, []) end

  def do_write(module, write_args),
    do: fn -> apply(module, :write, write_args) end

  def __after_compile__(env, _bytecode) do
    :functions
    |> env.module.__info__()
    |> Keyword.get_values(:write)
    |> case do
      [] -> raise "`write/0` _or_ `write/1` is required"
      [0] -> :ok # no args
      [1] -> :ok # with args
      [_] -> raise "Arity `0` _or_ `1` please"
      [_|_]  -> raise "Either `write/0` _or_ `write/1` please"
    end
  end
end
  1. Followed by composition:
    text_writer.ex
defmodule TextWriter do
  defstruct [:writer]

  @type wrt :: IWriter

  @opaque t :: %__MODULE__{
    writer: wrt
  }

  @spec new(writer :: IWriter) :: TextWriter.t()
  def new(writer) do
    %__MODULE__{
      writer: writer
    }
  end

  @spec write_with(writer :: IWriter) :: :ok
  def write_with(writer), do: writer.write()

  @spec write_with(writer :: IWriter, args :: any()) :: :ok
  def write_with(writer, args), do: writer.write(args)
end

And a sample implementation:
dummy_writer.ex

defmodule DummyWriter do
  use IWriter

  @type t :: __MODULE__

  def write(), do: :dummy
end

Assuming the following invocation:

    nw = TextWriter.new(DummyWriter)
    nw.writer.write()

The drawback, one amongst many, is that Dialyzer does not help us here.

Some questions:

  • Interface type - are there any plans for supporting it when proper type-system occurs in Elixir?
  • Are there any relevant approaches for compile-time dependency injection in Elixir as for now?
  • Are there any libraries out there that support all 4 dependency injection types (constructor injection, parameter injection, method injection, ambient context)?

…or maybe I’m thinking/doing something wrong? Please let me know.

Most Liked

D4no0

D4no0

I have a feeling that this looks like class reinvention from languages like c# and java.

What is the actual gain of having the IWriter call the actual functions from the modules you define? if that is only to enforce the IWriter type for specs there are easier methods to do that, putting your data in a struct of type IWriter.

That aside, by using apply/3 you lose all the compile-time power as apply is executed at runtime, so dialyzer cannot solve your types at compile-time.

I find it as cumbersome - an obstacle that effectively stops me from considering Elixir at production whether it is small or medium-size project., not even mentioning larger ones.

This is quite sad to hear, as I think getting rid of classes makes the code much more readable and maintainable in the long run. Maybe instead of trying to fit elixir to the way things are done in c#, you should take a step back and learn how things are done in functional languages.

cevado

cevado

I’m too late in the discution but the simplest way of doing dependency injection in any functional language is just passing a function. there are ways to define a contract to be followed(behaviours, that some people already mentioned), but this is loosely restrict by the runtime.
Going with functions, you could have something like:

def write_with(writer) when is_function(writer, 0), do: writer.()
def write_with(writer, args) when is_function(writer, 1), do: writer.(args)
def write_with(writer, args) when is_function(writer), do: apply(wrter, args)

edit:
Usually I go with behaviours for stuff that I need a set of functions that need to be implemented and to be used together.

dimitarvp

dimitarvp

After reading your code and post, I am still not 100% sure what you are after. “Dependency injection” is just a tool, and tools are used to achieve goals. What’s your goal?

If you want to have a discrete set of implementors of a certain behaviour / protocol (the Elixir meanings of them) and then look them up / use them wherever the behaviour / protocol is needed then that can be done fairly easily and we can help you get there.

You do need to show an open mind however; insisting that Elixir must have what C# has is… not an interesting discussion. Elixir has the tools to achieve similar goals.

Where Next?

Popular in Questions Top

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
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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Other popular topics Top

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
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
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
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
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

We're in Beta

About us Mission Statement