How to store state in module?

I think there are two “default” ways to handle state (and a lot more specific ones):

  • Store them in the client process
  • Store them in a dedicated process

Because Elixir is really good with processes people sometimes expect everything they code to do “process-y” stuff. But if you can, i think, it is recommended to start simple and do not introduce processes if you don’t need to. Your first sentence makes me think, that might work for you.

As an example: You have a module TodoList with a function add/1 that adds one item to the list. You might think “How / Where do i keep that list, so calling add/1 three times keeps all the old entries still there?” The easiest answer is "Just return the data to the caller and let them keep the state around! So instead of

defmodule TodoList do
  def add(item) do
    # Where does before come from?!
    [ item | before ]
    :ok
  end
end

you use

defmodule TodoList do
  def add(state, item) do
    # renamed "before" to "state", so the
    # concept hopefully becomes clearer
    [ item | state ]
  end
end

so the caller of your client keeps the state around and hands it to you for you to work on it.

2 Likes