I am getting my head around the ephemeral style of Elixir and where I should rebind inside my function calls or outside. Can someone advise on what the standard practice is…
Rebinding outside function call
defmodule MapModifier end
def modify_map(map) do
%{map | some_property: "abcd"}
end
end
outside_map = %{}
outside_map = MapModifier.modify_map(outside_map)
Rebinding inside function call
defmodule MapModifier end
def modify_map(map) do
map = %{map | some_property: "abcd"}
end
end
inside_map = %{}
MapModifier.modify_map(inside_map)
I have found myself using both in my code so far and wondering which approach would be advised… For example, one of my functions is called change_state and it kinda made sense for me for change_state to rebind inside the function… but not sure if I am doing it right…
You are setting yourself up for all kinds of cognitive dissonance by using the word “modify”.
What you are doing is creating a new map with an added property and returning that from the function. You can never modify the inputs, and you can only access the return result of the function from outside the function.
There is absolutely no difference in your two modify_map functions.
Remember that we transform data, from one thing (input), into something else (output) and where the output is always a copy (so the original is always left intact).
If you do this:
defmodule MapModifier do
def modify_map(map) do
map = %{map | some_property: "abcd"}
end
end
inside_map = %{some_property: "aaa"}
MapModifier.modify_map(inside_map)
inside_map
You’ll see it hasn’t changed inside_map at all, hence you’ll need to rebind it as per your first example.