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

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews