overcomeoj

overcomeoj

When to use perform_action("type", ...) vs perform_type(...)

What is the community guidelines on when you should pattern match a function vs when you should write its own? Eg:

Style 1

Extract something to match on and pass all the data down:

def perform_action(%{action: type} = data), do: perform_action(type, data)
def perform_action(:save, data), do: :ok
def perform_action(:delete, data), do: :ok
def perform_action(:revert, data), do: :ok
def perform_action(_, data), do: :error

Pros

  • Easier to organize like with like?
  • Allows flexibility in what data should contain at each handler
    • Including error handling (checking for required keys, etc)

Cons

  • Only one @doc block allowed
  • All functions are public (may not really be an issue)

Style 2

Get type and then call specific:

def perform_action(%{action: type} = data) do
  case type do
    :save -> perform_save(data)
    :delete -> perform_delete(data)
    :revert -> perform_delete(data)
    _ -> :error
  end
end

def perform_save(data), do: :ok
def perform_delete(data), do: :ok
def perform_revert(data), do: :ok

Pros

  • Can have per-function @doc blocks
  • Still flexible in what “downstream” functions accept and error handling is local to them
  • Probably easier to write “sub match” function headers for each action (eg: perform_save(%{sneaky: true} = data))
  • Specific functions can be private if needed
  • Lists all supported operations in one place?

Cons

  • First case could get very large?

Style 3

Extract specific data from top and pass down to functions:

def perform_action(%{action: type} = data) do
  case type do
    :save -> perform_save(data.id, data.content)
    :delete -> perform_delete(data.id)
    :revert -> perform_delete(data.id, data.date)
    _ -> :error
  end
end
def perform_save(id, content), do: :ok
def perform_delete(id), do: :ok
def perform_delete(id, date), do: :ok

Pros

  • @doc per function
  • More explicit interfaces, very obvious that save needs id + content.

Cons

  • Puts “must have key” checks in first function, which might bloat,
    • Though it could match on the type before dispatching to the specific
      function (but maybe thats just #1 with more steps…

From this extremely scientific research, it seems that #2 is maybe the best? Mostly because you can have per-function docs (though if they’re private this doesn’t actually count, @docp when?) It also seems really common with OTP to just have one named function and match on literally everything too but this is probably more a side effect of needing a generic interface - not intentionally blessed?

I am sure the most appropriate answer is, “well it depends.”, but discarding that, what does the community like to write?

Most Liked

sodapopcan

sodapopcan

If you’re dispatching based on external data (like a message) use pattern matching, but if you’re implementing known domain behaviour, definitely use a function for the various reasons you mentioned. Concrete concepts should have concrete names like Accounts.login_user or for CRUD operations Accounts.update_user. This way, you’re explicitly naming things your app does. This is especially true with CRUD because it’s highly possible that not all of your entities will support the full set of CRUD operations, eg, maybe you can only hide a post but never actually delete it. This would be far less discoverable if you’re passing atoms to a generic perform_action function (this is one thing I don’t miss about ORMs that automatically give you all CRUD actions whether you want them or not). On the other hand, things like GenServer use pattern matching as they are providing an extremely generic API to an abstract concept and, as you likely know, it’s super common to wrap their implementations in concrete function calls.

RudManusachi

RudManusachi

In this particular case they all could be variants of the same function pattern matching on action type right in the function head

def perform_action(%{action: :save} = data), do: :ok
def perform_action(%{action: :delete} = data), do: :ok
def perform_action(%{action: :revert} = data), do: :ok
def perform_action(data), do: :error

But to your question:
You probably have seen examples when private functions have the same name as public function but prefixed with do_ like

def perform_action(%{action: type} = data)  do
  do_perform_action(type, data)
end

defp do_perform_action(:save, data), do: ...
...

So that pattern is discouraged now[0] in favor of coming up with a better name (however, you still could find examples even in the source code of elixir, e.g. here)

That would make something in between Style 1 and Style 2
Name public and private functions differently from each other, but all private functions could have the same name.

def perform(%{action: type} = data), do: perform_action(type, data)

defp perform_action(:save, data), do: :ok
defp perform_action(:delete, data), do: :ok
defp perform_action(:revert, data), do: :ok
defp perform_action(_, data), do: :error

[0] - Add describe and module attributes by blatyo · Pull Request #9181 · elixir-lang/elixir · GitHub

Where Next?

Popular in Questions Top

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
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
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 Postg...
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
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
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New

We're in Beta

About us Mission Statement