Write Better Elixir Code

Blackode
Blackode
Mar 26 · 5 min read

If Condition & Value

Requirement

Don’t Do

new_status = 
if status == "True" do
true
else
false
end

Do

new_status = status == "True"

Testing Screenshot

Condition by Pattern Matching

Requirement

Don’t Do

is_map_has_keys = Map.has_key(map, :name) && Map.has_key?(map, key2)

Do

is_map_has_keys = match?(%{name: _, age: _}, map)

Testing Screenshot

Checking nil value in if condition

Don’t Do

feeling = 
if bank_balance == nil do
" I am sad :("
else
"I am happy :)"
end

Do

feeling = 
if bank_balance do
" I am happy :)"
else
"I am sad :("
end

Testing Screenshot

String Pattern Matching

Requirement

Don’t Do

currency = "$500"
[currency_value] = String.split(currency, "$", trim: true)

Do

"$"<> currency_value = currency

Testing Screenshot

Debug like a Pro-Programmer

Requirement

Don’t Do

#Filename: server.iex defmodule Server do
def send_packet(host, port, packet) do
IO.inspect host, label: "host"
IO.inspect port, label: "port"
IO.inspect packet, label: "packet"
end
end

Do

defmodule Server do  require IEx
def send_packet(host, port, packet) do
IEx.pry()
end
end

Testing Screenshot

In Case Don’t match for Conditions

Requirement

Don’t Do

role = 
case admin? do
true ->
"Admin"
false ->
case sub_admin? do
true ->
"Sub Admin"
false ->
"General User"
end
end

Do

role =
cond do
admin? ->
"Admin"
sub_admin? ->
"Sub Admin"
true ->
"General User"
end

Testing Screenshot

Safe side Condition Evaluation

Requirement

programmer1 = %{has_girlfriend: true, lang: "Elixir", type: "functional"}
programmer2 = %{lang: "C", type: "structured"}

Don’t Do

iex> if programmer1.has_girlfriend, do: "Lucky Guy", else: "Unlucky"
"Lucky Guy"
iex> if programmer2.has_girlfriend, do: "Lucky Guy", else: "Unlucky"
(KeyError) key :has_girlfriend not found in: %{lang: "C", type: "structured"}

Do

iex> if programmer1[:has_girlfriend],  do: "Lucky Guy", else: "Unlucky"
"Lucky Guy"
iex> if programmer2[:has_girlfriend], do: "Lucky Guy", else: "Unlucky"
"Unlucky"

Testing Screenshot

https://t.me/blackoders
if worth_clapping, do: “clap”, else: nil

blackode

Coding, thoughts, and ideas.

Blackode

Written by

Blackode

Wrong CODE takes U to the right BUG 🐞 coding, thoughts & ideas

blackode

blackode

Coding, thoughts, and ideas.