style
Elixir coding style and conventions. Use when writing idiomatic Elixir, avoiding bang functions in business logic, using pattern matching for error handling…
от vinnie357★ 30 звёзд на GitHub
Установить style в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Elixir Style and Conventions
This skill complements elixir:anti-patterns — that skill covers what to avoid; this one covers what to do instead.
Tagged Tuples and Return Conventions
Elixir functions signal success or failure through return values, not exceptions.
Standard return shapes:
# Two-element ok/error tuples (most common)
{:ok, result}
{:error, reason}
# Bare atoms for side-effect operations
:ok
:error
# Richer error tuples for typed failures
{:error, :not_found}
{:error, :unauthorized}
{:error, %Ecto.Changeset{}}
Why this convention matters:
Pattern matching on tagged tuples is the foundation of Elixir error handling. When every function in a call chain returns {:ok, _} or {:error, _}, with expressions can thread success values through and exit early on the first failure — without nested if or try/rescue.
# Callers can match exhaustively
case fetch_user(id) do
{:ok, user} -> render_profile(user)
{:error, :not_found} -> send_resp(conn, 404, "Not found")
{:error, reason} -> send_resp(conn, 500, inspect(reason))
end
Logger over IO.puts
All application output goes through Logger. Do NOT use IO.puts/1, IO.write/1, or :io.format/2 from application code. Logger respects log levels, supports metadata, and routes through the configured backends (console, file, structured log shippers). IO.puts writes directly to stdout regardless of log level and bypasses backend configuration.
# WRONG — IO.puts("worker started")
# CORRECT
Logger.info("worker started")
Logger.info("worker started", worker_id: id, module: __MODULE__)
Flush concerns at shutdown go through Logger configuration (Logger.flush/0 in an at_exit, or the :logger_std_h flush settings), not by bypassing Logger to write directly. The only legitimate use of IO in app code is reading from / writing to a specific IO device the user requested (e.g., a CLI tool's stdout output, where the OUTPUT IS the contract).
Bang Functions: When to Avoid
The Convention
Every standard library function with a ! variant follows this contract:
| Non-bang | Bang |
|---|---|
File.read/1 → {:ok, content} or {:error, reason} |
File.read!/1 → content or raises |
Map.fetch/2 → {:ok, value} or :error |
Map.fetch!/2 → value or raises KeyError |
Repo.insert/1 → {:ok, struct} or {:error, changeset} |
Repo.insert!/1 → struct or raises |
Repo.get/2 → struct or nil |
Repo.get!/2 → struct or raises Ecto.NoResultsError |
When Bangs Are Appropriate
Use bang functions when failure represents a programming error or an invalid system state that should crash loudly:
# Application startup — missing config is a bug, not a user error
def start(_type, _args) do
api_key = Application.fetch_env!(:my_app, :stripe_api_key)
# ...
end
# Seeds and migrations — invalid data is a developer error
Repo.insert!(%User{email: "[email protected]", role: :admin})
# Pipelines operating on already-validated, known-good data
"hello world"
|> String.split()
|> Enum.map(&String.capitalize/1)
|> Enum.join(" ")
# Tests asserting expected state
user = Repo.get!(User, user_id)
When to Avoid Bangs
Avoid bang functions wherever failure is a normal, expected outcome:
# BAD: user input can always fail validation
def create_user(conn, %{"user" => params}) do
user = Repo.insert!(%User{email: params["email"]}) # raises on validation failure
json(conn, %{id: user.id})
end
# GOOD: handle the error path explicitly
def create_user(conn, %{"user" => params}) do
case %User{} |> User.changeset(params) |> Repo.insert() do
{:ok, user} -> json(conn, %{id: user.id})
{:error, changeset} -> conn |> put_status(422) |> json(changeset_errors(changeset))
end
end
# BAD: external APIs can return 404, 500, network errors
def fetch_payment(payment_id) do
Stripe.PaymentIntent.retrieve!(payment_id) # raises on API error
end
# GOOD: return a tagged tuple, let the caller decide
def fetch_payment(payment_id) do
case Stripe.PaymentIntent.retrieve(payment_id) do
{:ok, payment} -> {:ok, payment}
{:error, %{code: "resource_missing"}} -> {:error, :not_found}
{:error, reason} -> {:error, reason}
end
end
Rule of thumb: if a user action, external service, or DB constraint could cause the failure, use the non-bang variant and handle it.
Pattern Matching for Error Handling
with for Chaining Dependent Operations
Use with when multiple steps must all succeed, and any failure should short-circuit to an error response:
def register_user(params) do
with {:ok, validated} <- validate_registration_params(params),
{:ok, user} <- create_user(validated),
{:ok, _profile} <- create_default_profile(user),
{:ok, _email} <- send_welcome_email(user) do
{:ok, user}
else
{:error, %Ecto.Changeset{} = cs} -> {:error, {:validation_failed, cs}}
{:error
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/ecto-data-shapes.md
FAQ
Что делает скилл style?
Elixir coding style and conventions. Use when writing idiomatic Elixir, avoiding bang functions in business logic, using pattern matching for error handling, or designing Ecto schemas as the single source of truth for data validation.
Как установить скилл style?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл style запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…