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

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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
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
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
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
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
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement