stratacast

stratacast

Function with many arguments design

Hey everyone!

This is my first time posting on here, and I’m getting started with writing some real Elixir code! I’m not new to programming, but I also wouldn’t call myself a programmer, more of a hobbyist since I do a lot more with systems and security.

Anyhay, I really like to learn coding design when I trying new languages, so when I create a function in a module, I want to do it the right way. In my code I’m writing right now, I am writing some functions in a module that will be accepting many arguments, and the majority of them are going to be optional with default values, or optional with nil and if it’s nil it will get tossed.

With that context, if I have a function with say, 10 arguments, how would you write that? My thought is to have it something like this:

  def testfunc(
        arg1,
        arg2,
        arg3 \\ "default",
        arg4 \\ "default1",
        arg5 \\ nil
      ) do
    IO.puts("Hello")
  end

Is that acceptable in the Elixir world?

Most Liked

jeremyjh

jeremyjh

10 arguments is pretty unwieldy. What you’ll see more commonly is a data structure defined with defstruct that is used in the module. Maybe a couple of constructors, and then functions that accept other args and implement logic to add to the structure, and then functions that consume it.

The other pattern you will see is the options pattern - this is for when you have one-three args that are required and several optional arguments. You define the last argument as a Keyword list. Elixir has syntax sugar so you don’t have to wrap that in a list constructor.

seanmor5

seanmor5

Author of Genetic Algorithms in Elixir

What he’s saying is this:

defmodule MyModule do
   @enforce_keys [:arg1, :arg2, :arg3]
   defstruct :arg1, :arg2, :arg3, arg4: “default”, arg5: “default”

   def testfunc(%__MODULE__{} = params) do
      ...
   end
end

You can then access the arguments in the params variable. Enforce keys requires specific arguments be specified.

al2o3cr

al2o3cr

If your argument list is always used together, the struct approach can be powerful.

If the arguments are more ad-hoc, one approach you’ll see in other languages is named arguments. Elixir doesn’t specifically have named arguments, but you can get close with a keyword list:

def some_func(required_arg_1, required_arg_2, opts \\ []) do
  # extract optional args from opts with Keyword.get(opts, :optional_arg_name, "default value")
end

# call sequence
some_func("foo", "bar")
some_func("foo", "bar", baz: "wat")

if you have a LOT of optional arguments, you might even do something like:

def some_func(required_arg_1, required_arg_2, kw_opts \\ []) do
  opts = Enum.into(kw_opts, %{optional_arg_1: "default", optional_arg_2:: false, ...})
  # can now use opts.optional_arg_1 etc
  # or pattern-match the map
end

I first encountered this technique in this post: Passing in options: Maps vs. Keyword lists

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <...
New
jaysoifer
Is there a way to rollback a specific migration and only that one ("skipping" all the other ones)? Would mix ecto.rollback -v 2008090...
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

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
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
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
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I fore...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I'm a nov...
New
hariharasudhan94
Lets say i have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => "XX...
New

We're in Beta

About us Mission Statement