DEV Community

Discussion on: Any tips for someone just starting out learning Elixir?

Collapse
 
hugecoderguy profile image
Christian Kreiling

In learning Elixir, it's important to think functionally. You're coming from languages that are traditionally referred to as object-oriented languages, but they still allow you to program functionally.

Functional programming might seem intimidating at first, but it's easiest to think about the difference with this simple JavaScript example:

function sayHello(name) { console.log(`Hello, my name is ${name}`) }

function Person(name) {
  this.name = name;
}

Person.prototype.introduce = function() { sayHello(this.name) }
Person.prototype.getName = function() { return this.name }

function introduceUsingFP(person) { sayHello(person.getName()) }

var harryPotter = new Person("Harry Potter");

# OOP
harryPotter.introduce();
// Hello, my name is Harry Potter

# FP
introduceUsingFP(harryPotter);
// Hello, my name is Harry Potter

Notice that in OOP, you have an object which has data and behavior (the introduce() function). In FP, you have an object with data, but its behavior is not a part of the object.

So in Elixir you'd have a module Person, which defines a struct using defstruct. It's best-practice to then implement functions in this module which accept an instance of the struct, and do something to/with it.

defmodule Person do
  defstruct [:name]

  def introduce(%Person{} = person) do
    IO.puts("Hello, my name is " <> person.name)
  end
end

harry_potter = %Person{name: "Harry Potter"}
Person.introduce(harry_potter)
# Hello, my name is Harry Potter

You will witness this in many libraries in Elixir. Ecto's changeset functions are a great example. All of the validation functions in the Ecto.Changeset module accept an Ecto.Changeset struct and return an updated Ecto.Changeset struct.

My Elixir knowledge really took off after I read the book Programming Elixir ≥ 1.6: Functional |> Concurrent |> Pragmatic |> Fun. It starts with basic Elixir, but by the end of the book familiarizes you with complex topics such as Open Telecom Platform (OTP) and metaprogramming using macros. I now use it as reference when I need some clarification on concepts ranging in complexity.