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 https://github.com/joshnuss/design-patterns-in-elixir/blob/master/factory/run.exs

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 #6
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.

NobbZ

NobbZ

No.

Pass in the actual module name… def process_order(module), do: module.process() and you are ready to go.

sasajuric

sasajuric

Author of Elixir In Action

I agree. The mechanics are inevitably somewhat different, but I think the idea is in its spirit similar: we’re consolidating a conditional and extracting it into a dedicated place. I think this is a useful pattern, even in an FP language.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New

Other popular topics Top

William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement