Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Types in Elixir

Types in Elixir

Use cases and Examples of a good use of types IMHO

tetiana12345678

February 20, 2019
Tweet

More Decks by tetiana12345678

Other Decks in Programming

Transcript

  1. @tetiana12345678 Types Great for validations def changeset(user, params \\ %{})

    do user |> cast(params, [:name, :email, :age]) |> validate_required([:name, :email]) |> validate_format(:email, ~r/@/) |> validate_inclusion(:age, 18..100) |> unique_constraint(:email) end %Ecto.Changeset{} -> %Ecto.Changeset{}
  2. @tetiana12345678 Types Great for data transformation plug :accepts, ["html"] plug

    :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers %Phoenix.Conn{} -> %Phoenix.Conn{}
  3. @tetiana12345678 Types Pattern match on a type def handle_message(%EmailsSent{} =

    msg) do save_message_to_db(msg) end def handle_message(_), do: :unknown_message * Type safety
  4. @tetiana12345678 Types Structs Adding a new key to a struct

    is easy. Other functions using %Response{} will still work. defmodule MyModule do def handle_response(a, b), do: :ok end defmodule MyModule do def handle_response(%Response{a: a, b: b}), do: :ok end
  5. @tetiana12345678 Types Further learning - Check Elixir Protocols - Check

    dialyzer and dialyxir library - Design by Contract in Elixir “Let it crash” meets “It shouldn’t crash” https://www.youtube.com/watch?v=OcbE6nL1QEk - Chris Keathley - Well Typed Elixir https://www.youtube.com/watch? v=Jxfodke3oX8