Guard Clause Type Error Checking?

Hello.

I’ve been looking for the best way to express an Agent that only manages the state of a single boolean. I am looking for feedback on the style I am using here, with a guard clause and an additional function head to handle the error case. Here is what I have:

defmodule BooleanState do
  use Agent
  def start_link, do: Agent.start_link(fn -> false end, [name: __MODULE__])
  def get, do: Agent.get(__MODULE__, fn state -> state end)
  def set(state) when is_boolean(state) do
    case state do
      false -> Agent.update(__MODULE__, fn _ -> false end)
      true -> Agent.update(__MODULE__, fn _ -> true end)
    end
  end
  def set(state) do
    raise ArgumentError, message: "set/1 requires argument of type boolean. Got: '" <> IO.inspect(state) <> "'"
  end
end

What do you think? I can’t decide if I like this approach, but I do not know a better way to achieve this same result.

Well this could easily become:

  def set(state) when is_boolean(state) do
    Agent.update(__MODULE__, fn _ -> state end)
  end
1 Like

That’s definitely a little cleaner. Thanks. :slight_smile:

1 Like

The new code looks like this:

defmodule BooleanState do
  use Agent
  def start_link, do: Agent.start_link(fn -> false end, [name: __MODULE__])
  def get, do: Agent.get(__MODULE__, fn state -> state end)
  def set(state) when is_boolean(state) do
    Agent.update(__MODULE__, fn _ -> state end)
  end
  def set(state) do
    raise ArgumentError, message: "set/1 requires argument of type boolean. Got: '" <> IO.inspect(state) <> "'"
  end
end

I’m still not sure I like this method of error checking.

It is a common way of error checking since there is no type system. I often do precisely the same. :slight_smile:

However, since you are not doing anything special I’d just leave your error handling case out. You get really nice error message from elixir if so here soon (if compiled with OTP 20). :slight_smile:

1 Like