Why is this good? In my own opinion, this provides several benefits that makes it easier to program but specifically in elixir it can be used to determine the flow of your program from the function definition.
In a functional first language, you have one CENTRAL location that holds the state of your program that your program can act on. In object oriented languages, you typically would break this state up into different objects to "model" your program. This means you will typically have state in several locations and you have to "ask" questions about that state in one or more location before acting in your program. As an example in C#:
var ironMan = new IronMan(); var hulk = new Hulk(); if (ironMan.IsFlying == hulk.IsJumping) new Thor().StartFlying();
In Elixir the same code would look like this:
defmodule Marvel do @marvel %{ :ironman => %{ :is_flying => true }, :hulk => %{ :is_jumping => true}} def fight(), do: start_flying(@marvel) def start_flying( %{ :ironman => %{ :is_flying => true }, :hulk => %{ :is_jumping => true}}), do: fly def fly(), do: IO.puts "flying" end
In elixir, the function only executes when the data set "looks" like the data that is passed into the start_flying function. I love this language feature because it communicates to someone reading my code what I want to happen (the name of the function) when the data is shaped a certain way. This means that the reader ONLY has to look at the function definition to determine the flow of the program. In an imperative language, the reader is forced to read the body of the function to determine the flow of the program.
Even though I have been programming in imperative languages my entire career, I find it much harder to program in an imperative way. It's like having to ask your wife, son, mother, and father a question before you run an errand instead of just having your wife telling you everything you need to know up front before you leave the house to run an errand.
Using this analogy, it means that if you have a "question" later, you have to call one of the 4 people to ask your question in the imperative approach as opposed to using pattern matching and "plucking" the information you need out of the original information given to you by your wife before you left the house :)
Even though I have been programming in imperative languages my entire career, I find it much harder to program in an imperative way. It's like having to ask your wife, son, mother, and father a question before you run an errand instead of just having your wife telling you everything you need to know up front before you leave the house to run an errand.
Using this analogy, it means that if you have a "question" later, you have to call one of the 4 people to ask your question in the imperative approach as opposed to using pattern matching and "plucking" the information you need out of the original information given to you by your wife before you left the house :)