LoginSignup
8
0

【Elixir アンチパターン】 booleanか、atomどちらを使うか?

Last updated at Posted at 2023-12-20

Elixir アンチパターンを読んでみる

boolean-obsessionを見てみます。

アンチパターン

defmodule MyApp do
  def process(invoice, options \\ []) do
    cond do
      options[:admin] ->  # Is an admin
      options[:editor] -> # Is an editor
      true ->          # Is none
    end
  end
end

お勧めの実装

defmodule MyApp do
  def process(invoice, options \\ []) do
    case Keyword.get(options, :role, :default) do
      :admin ->   # Is an admin
      :editor ->  # Is an editor
      :default -> # Is none
    end
  end
end

admin権限かeditor権限の切り替えの実装どっちが良いか?という話です。

アンチパターンの方は、optionsのキーの該当する権限がtrueかfalseで判定する。おすすめの実装は、:roleの値に権限に応じたatomを入れる方式。

アンチパターンの方では、複数の権限がtrueになる場合は発生してその場合優先度の高いほうの動作になる。具体的にはcond文の先に書かれた権限の動作になります。
roleの値はどれか一つというのが要件だったら、おすすめの方法のようにした方が明確です。
速度面でもbooleanの値もatomの一つなので違いはありません。

ONかOFFしかないものであってもbooleanではなくatomにした方がわかりやすい場合の例も書かれてました。

MyApp.update(invoice, approved: true)
MyApp.update(invoice, status: :approved)

どっちでもいい感じですが、状態が増える事も考えられる感じだったらstatusの方がよさそうだと私も思います。

booleanに固執せず、atomで表現する事も検討してみましょう。

8
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
0