threeaccents

threeaccents

Dealing with private and public function default conflicts

I wanted to see how others deal with private and public function defaults conflict. In my context I like to have public functions that take the current_user from the request what ever other arguments are needed with a “matching” private function that only takes the arguments after the public function does some authorization.

here is a quick example of update user

# user context
def update_user(%User{} = current_user, %UpdateUser{} = update_user) do
    with :ok <- authorize(:update_user, current_user, update_user),
        {:ok, updated_user} <- update_user(update_user) do
        # some logic
    end
end

defp update_user(%UpdateUser{} = update_user) do
  # some logic
end

This works great 95% of the time but sometimes certain functions need to have default parameters

def list_company_users(%User{} = current_user, company_id, filters \\ %{}) do
    # some logic
end

defp list_company_users(company_id, filters) do 
  # some logic
end

For situations like this there is a conflict of having a private and a public function
defp list_company_users/2 conflicts with defaults from list_company_users/3

As a hacky workaround I made the arguments of the private function a tuple.

defp list_company_users({company_id, filters}) do 
  # some logic
end

I was curious if anyone else used a similar pattern and what solution they’ve taken when running into this issue.

Marked As Solved

sanswork

sanswork

Personally I’d use different names for the private functions. To add to this I know _function is pretty common for private, personally I use function/do_function

def update_user
defp do_update_user

Anything will work as long as you’re consistent though then you don’t have to go check the def.

Also Liked

dimitarvp

dimitarvp

Seconded, I use the do_* private functions notations myself. Mostly because I have no better idea. :smiley:

Aetherus

Aetherus

It seems that do_* has become a convention :grinning_face_with_smiling_eyes:
By the way, I follow this convention, too.

eksperimental

eksperimental

This is one of my favorite patterns, the _guarded suffix. You do all your guard checks in your public function, and you delegate to a private one and call it recursively if needed, without checking for a guard again and increasing performance.

This is the current implementation for Keyword.update/4

  @spec update(t, key, default :: value, (existing_value :: value -> new_value :: value)) :: t
  def update(keywords, key, default, fun)
      when is_list(keywords) and is_atom(key) and is_function(fun, 1) do
    update_guarded(keywords, key, default, fun)
  end

  defp update_guarded([{key, value} | keywords], key, _default, fun) do
    [{key, fun.(value)} | delete(keywords, key)]
  end

  defp update_guarded([{_, _} = pair | keywords], key, default, fun) do
    [pair | update_guarded(keywords, key, default, fun)]
  end

  defp update_guarded([], key, default, _fun) do
    [{key, default}]
  end
kokolegorille

kokolegorille

There is no way to detect if You call list_company_users/3 without filter, and list_company_users/2

You might add guard clauses…

# Use when is_binary if You use binary id.
def list_company_users(%User{} = current_user, company_id, filters \\ %{}) when is_integer(company_id) do
    # some logic
end

defp list_company_users(company_id, filters) when is_map(filters) do 
  # some logic
end

I also prefer do_* for private functions…

You might also check how to use function’s signature

threeaccents

threeaccents

Thank you for all the replies. It does seem the Elixir community has a convention of doing do_* for private functions. I’m going to try it out and see how it feels.

Thank you everyone for the replies!

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement