Slide 1

Slide 1 text

Types

Slide 2

Slide 2 text

@tetiana12345678 Types Why Types? Bad data -> Bugs -> Headaches Types to the rescue! \0/

Slide 3

Slide 3 text

Use cases & Examples

Slide 4

Slide 4 text

@tetiana12345678 Types Types at the boundary

Slide 5

Slide 5 text

@tetiana12345678 Types Types at the boundary

Slide 6

Slide 6 text

@tetiana12345678 Types Types at the boundary

Slide 7

Slide 7 text

@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{}

Slide 8

Slide 8 text

@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{}

Slide 9

Slide 9 text

@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

Slide 10

Slide 10 text

@tetiana12345678 Types Struct vs Map * Can use @enforce_keys

Slide 11

Slide 11 text

@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

Slide 12

Slide 12 text

@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