ENCAPSULATION & POLYMORPHISM
CLASSES VS MODULES, PROTOCOLS, AND STRUCTS class Foo def initialize(bar, quux) @bar = bar @quux = quux end def add @bar + @quux end end module Bar def add(a, b) a+b end end Foo.new(1, 2).add
defmodule Foo do defstruct bar: nil, quux: nil def add(%Foo{bar: b, quux: q}), do: b + q end
Interface, not implementation
Implementation
Implementation
{
defprotocol Mathy do def add(struct) def add(a, b) end
{ {
defimpl Mathy, for: Foo do def add(%Foo{bar: b, quux: q}), do: b + q end defimpl Mathy, for: Bar do def add(%Bar{a: a, b: b}), do: a + b end