ExSlop.Check.Warning.GenserverAsKvStore (ExSlop v0.3.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

A GenServer that implements handle_call({:get, key}, ...) with a body that just calls Map.get(state, key) is reimplementing a key-value store. The BEAM already provides Agent and ETS for this.

# bad — GenServer as a dumb key-value wrapper
defmodule MyCache do
  use GenServer

  def handle_call({:get, key}, _from, state) do
    {:reply, Map.get(state, key), state}
  end

  def handle_call({:put, key, value}, _from, state) do
    {:reply, :ok, Map.put(state, key, value)}
  end
end

# good — use Agent
defmodule MyCache do
  use Agent

  def start_link(initial) do
    Agent.start_link(fn -> initial end, name: __MODULE__)
  end

  def get(key), do: Agent.get(__MODULE__, &Map.get(&1, key))
  def put(key, value), do: Agent.update(__MODULE__, &Map.put(&1, key, value))
end

# good — use ETS
:ets.new(:cache, [:named_table, :public])
:ets.insert(:cache, {key, value})
:ets.lookup(:cache, key)

Check-Specific Parameters

There are no specific parameters for this check.

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.