fireproofsocks

fireproofsocks

__using__ modules to share private functions... ordering functions?

This is a code style question (mostly?). I’m using use and the __using__ macro to share private functions between other modules. The functions have the same name and arity: the idea is that they get called recursively to validate input and accumulate errors. This works well, EXCEPT for one thing that looks… smelly: Because of how matching works, the most specific function clauses are declared first, and then the most general catch-alls appear last. What this means is that my modules have to put the use clauses BELOW, like this:

defmodule MyThing do

    defp foo(%{very: "specific", match: "clause"} = args, acc) do
        # implementation...  then call the "shared" functions
        foo(args, acc) 
    end
 
    use FunctionsInSharedModule  # <--- down here!
end

My question is: is this bad form? Some style guides stat that use statements should appear near the top of the module declaration, and it’s easy to miss a use tossed into the bottom of the module. Am I being too sensitive? I’m trying to think of a more elegant way to structure this.

Your thoughts are welcome!

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

I believe you can replace injecting the code with this:

    defp foo(%{very: "specific", match: "clause"} = args, acc) do
        # implementation...  then call the "shared" functions
        foo(args, acc) 
    end
   defp foo(args, acc) do
     CommonValidations.foo(args, acc)
   end 

Then CommonValidations.foo gets to be a proper function instead of an injected one, with all the benefits of better error messaging.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Function calls are the easiest way to compose functions. If you want to indicate that a module or its functions are internal that’s what @doc false or @moduledoc false is great for that. Macros, and injecting functions with macros, have a place, but that’s generally when something about those functions would make them difficult or problematic to call directly. Really though this should be a last resort, and I think it is far more likely of a need in something like a library than in your application code.

If you are finding yourself needing use because you want to call other private functions then you need to take a seriously look at your module and figure out if you are treating it like a class.

If you still want to have some stuff in your common functions call functions within the specific module, use a behaviour, and pass the module name in to your common eg:

def foo(#specific stuff here) do
end
def foo(args, acc) do
  Common.foo(__MODULE__, args, acc)
end
al2o3cr

al2o3cr

A more idiomatic way to get the intended behavior ("add these clauses to the end of the module that called use FunctionsInSharedModule") is the @before_compile callback. For instance, it’s used to declare a catchall render function in Phoenix.View

fireproofsocks

fireproofsocks

That assumes that CommonValidations.foo is a public function, yes?
My use case is slightly more complex (I tried to keep things simple): I’m actually useing multiple modules to compose the set of functions/rules that make sense for each use case, so I have to think through how that might be affected…

gregvaughn

gregvaughn

While I agree with what Ben is saying – this may not be a good use of macros. If it is though, it is not a good use of use which is syntax sugar over require and direct macro call and is expected at the top of the file. However, if you made that a more explicit macro call, it would reduce the “smell”.

For example, replace:

use FunctionsInSharedModule

with something like:

FunctionsInSharedModule.foo_fallbacks()

and the necessary require FunctionsInSharedModule at the top of the file

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
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
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
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
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
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement