fireproofsocks

fireproofsocks

Factory Pattern in Elixir?

I’m working on a problem that requires that a vendor-specific module be loaded to handle vendor-specific tasks related to an order. I’ve been trying out the behaviours, and that all makes sense. Coming from an OO background, however, I’m feeling the need to have a factory in this case… where I want to load up the proper module that implements the given interface, then call the do_something method on it. Conceptually, it’s pretty common OO.

However, in Elixir, the best I’ve come up with is either a big case statement or a series of declared functions that rely on pattern-matching in their signatures to send the execution flow to a specific vendor module, e.g. something like this:

def process_order("vendor-one"), do: VendorOne.process()
def process_order("vendor-two"), do: VendorTwo.process()
def process_order("vendor-two"), do: VendorThree.process()

Or outlined more academically here design-patterns-in-elixir/factory/run.exs at master · joshnuss/design-patterns-in-elixir · GitHub

Is this idiomatic? Is there some other way to dynamically get a module name based on a parameter?

Marked As Solved

david_ex

david_ex

FYI you could use the following to get module names from strings:

my_module = "MyApp.VendorOne"
module_atom = String.to_existing_atom("Elixir." <> my_module)
module_atom == MyApp.VendorOne
# true

Edit: as indicated by others below (e.g. @sasajuric’s), there are some better & safer approaches to this, so probably use one of those instead…

Also Liked

imetallica

imetallica

Honestly, I don’t like the Factory pattern. I prefer to be a bit more data centric.

For example, each vendor has it’s own way to understand the orders, so you should have something like %VendorOneOrder{}, %VendorTwoOrder{}, etc… and they you apply the processing implementing a Protocol (ProcessableOrder). Then you implement all the declared functions of the protocol. For example:

defprotocol ProcessableOrder do
  def from_order(to_order, internal_order)
  def process(order)
end

And in each implementation, you do the following:

defimpl ProcessableOrder, for: VendorOneOrder do
  def from_order(vendor_one, %Order{vendor: "vendor-one"}), do: ...
  def process(order), do: ...
end

It will not solve the case problem, but at least you guarantee that the contract is kept in place if you add more Vendors. But it’s another approach to the same solution.

10
Post #5
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Relatedly, this fits in nicely if you can define a Behaviour https://elixir-lang.org/getting-started/typespecs-and-behaviours.html for the module that will do the processing.

sasajuric

sasajuric

Author of Elixir In Action

I definitely wouldn’t advise doing this, because it introduces a non-obvious coupling between the data in the database and the code. For example, if you refactor the code and don’t pay attention, the mapping is gone. Or even worse, some unwanted mapping might be introduced.

Instead, I’d make it explicit:

def vendor("vendor-one"), do: VendorOne
def vendor("vendor-two"), do: VendorTwo

I would then convert the string to the alias (module name) immediately after the data is loaded. Similarly, I’d convert it back to string before it’s persisted. If you’re using Ecto, you can write a type for that.

Last Post!

OvermindDL1

OvermindDL1

Just referencing modern day and what people would know it from. I’ve used factories way back since before C was standardized so I know it is very old pattern. ^.^;

This is the big key!!

You can put the ‘hardcoded’ map in the config files, then in the app anytime you need it access it via Application.get_env/2 and query it directly. You can even do that at compile-time to build up function matchers but by keeping it at run-time you can allow for it to be changed while the system is running to add/remove things to it without needing a hot code swap or reload. :slight_smile:

The configuration itself would just be a mapping of stringnames ↔ module names, or even full MFA’s if you want. :slight_smile:

Protocols are for dispatching on a type like a struct type so if you have that then absolutely yes, otherwise the plugin model is better (which you can also do via any arbitrary tag, like a string, with my ProtocolEx library ^.^).

Where Next?

Popular in Questions Top

Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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
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

Other popular topics Top

jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New

We're in Beta

About us Mission Statement