MMore

MMore

Hello Hello,

I have a bunch of function clauses (means one function, but different clauses to match for different input parameters). This function is basically an API handler.

def handle_event_type(event_type = "car_started", _params) do
  # do sth.   
end

def handle_event_type(event_type = "car_stopped", _params) do
  # do sth. else 
end

I wanna structure and organise a little bit for better readability according to the different business use cases. So my idea was to put the different function clauses in one file per use case and import those files back into my central API handler file to consolidate everything again.

But I get the following error:

== Compilation error in file lib/project/controllers/api_controller.ex ==
** (CompileError) lib/project/controllers/api_controller.ex:90: imported Project.ApiHandler.handle_event_type/2 conflicts with local function
(elixir 1.11.4) src/elixir_locals.erl:94: :elixir_locals.“-ensure_no_import_conflict/3-lc$^0/1-0-”/2
(elixir 1.11.4) src/elixir_locals.erl:95: anonymous fn/3 in :elixir_locals.ensure_no_import_conflict/3
(stdlib 3.14.1) erl_eval.erl:680: :erl_eval.do_apply/6
(elixir 1.11.4) lib/kernel/parallel_compiler.ex:314: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

Any other idea to organise everything better?

Showing Posts 1 to 2

Qqwy

Qqwy

TypeCheck Core Team

The error you get, is because when importing multiple modules that define a function with the same name,
the result is not “a single function” with the clauses combined.
Instead, the result is two functions, and ambiguity between them.

Multiple function clauses

def foo(1), do: "bar"
def foo(2), do: "baz"
def foo(_other), do: "qux"

are syntactic sugar for:

def foo(val) do
  case val do
    1 -> "bar"
    2 -> "baz"
    _other -> "qux"
  end
end

As soon as a module was compiled, all function clauses end up as case-statements, and the function is “finished”.
The only way to combine function clauses from multiple modules into the same function, is by exporting them at the AST (parsed-source-code) level (i.e. using macros), and combine these AST snippets.
However, this is almost always a bad idea as it will no longer be obvious where a particular event is handled. Instead, you’ll have to crawl through all files that contain some of the clauses. As such, you haven’t really gained anything by splitting the file this way: There is no separation of concerns between files.


But there is an alternative:

A relatively common approach I’ve seen used and used myself in the past, is to have the event_type be something “splittable” (either a list, or by e.g. pattern match on the front of the event type). For instance, by using / or : as “separator”, you might have events like customer:car:started, customer:car:stopped, billing:overdue, etc.
This then allows you to essentially create some event routing logic, spread out over multiple modules:

defmodule MainEventHandler do
  def handle_event(event_type, params) do
    dispatchable_event_type = String.split(event_type, ":")
    dispatch_event(dispatchable_event_type, params)
  end
  
  def dispatch_event(["customer" | rest], params), do: Customer.EventHandler.dispatch_event(rest, params)
  def dispatch_event(["billing" | rest], params), do: Billing.EventHandler.dispatch_event(rest, params)
  # etc.
end

defmodule Customer.EventHandler do
   def dispatch_event(["car" | rest], params), do: Customer.Car.EventHandler.dispatch_event(rest, params)
   # ... and add others here.
end

defmodule Customer.Car.EventHandler do
  def dispatch_event("started", params) do
    # ...
  end

  def dispatch_event("stopped", params) do
    # ...
  end
  # ... etc.
end

defmodule Billing.EventHandler do
  def dispatch_event(["overdue"], params) do
    # ...
  end
  # ... etc.
end
dimitarvp

dimitarvp

Generally: just don’t, you can’t achieve it the way you aimed at for the reasons @Qqwy explained excellently.

But if you really want to have some sort of routing, you might be better off just making one central router module which just delegates to a number of other modules.

Protocols I would advise against; you can make do without them for sure.

Finally, you can use behaviours and runtime hackery to dispatch to a compliant one but IMO that’s an overkill as well.

IMO just go for a router module that dispatches function calls to other modules. Standardize those modules somehow. Easiest way would be to just clump them up in one directory but if you really want to be able to find them at runtime, you can also make them implement a behaviour.

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews