From c5942e2a6822c284942b7ff939ac7c399d7964a7 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 25 Dec 2016 18:49:39 -0600 Subject: [PATCH] Add Same Functions Should Be Grouped Together as an elixir til --- README.md | 3 +- ...me-functions-should-be-grouped-together.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 elixir/same-functions-should-be-grouped-together.md diff --git a/README.md b/README.md index bf48a07..36cbd23 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_493 TILs and counting..._ +_494 TILs and counting..._ --- @@ -107,6 +107,7 @@ _493 TILs and counting..._ - [Root Directory Of A Project](elixir/root-directory-of-a-project.md) - [Round Floats To Integers](elixir/round-floats-to-integers.md) - [Run ExUnit Tests In A Deterministic Order](elixir/run-exunit-tests-in-a-deterministic-order.md) +- [Same Functions Should Be Grouped Together](elixir/same-functions-should-be-grouped-together.md) - [String Interpolation With Just About Anything](elixir/string-interpolation-with-just-about-anything.md) - [Updating Values In A Map](elixir/updating-values-in-a-map.md) - [Virtual Fields With Ecto Schemas](elixir/virtual-fields-with-ecto-schemas.md) diff --git a/elixir/same-functions-should-be-grouped-together.md b/elixir/same-functions-should-be-grouped-together.md new file mode 100644 index 0000000..c1e3002 --- /dev/null +++ b/elixir/same-functions-should-be-grouped-together.md @@ -0,0 +1,30 @@ +# Same Functions Should Be Grouped Together + +A favorite feature of Elixir is the function clauses that can be defined in +multiple ways with pattern matching. I've always grouped same-named function +clauses together. It seems like good form and it's what I see everyone else +doing. It also makes for readable, maintainable code. + +This is more than just personal preference though. It is the correct, +idiomatic way to organize your Elixir function clauses. The compiler will +let you know if anything gets out of place. + +Consider the following snippet of code: + +```elixir +defmodule MeterToLengthConverter do + def convert(:feet, m), do: m * 3.28084 + def convert(:inch, m), do: m * 39.3701 + def hello(), do: IO.puts "Hello, World!" + def convert(:yard, m), do: m * 1.09361 +end +``` + +It is syntactically correct, so it will compile. However, the compiler will +emit a warning like the following: + +``` +warning: clauses for the same def should be grouped together, def convert/2 +was previously defined (length_converter.ex:2) + length_converter.ex:5 +```