WestKeys

WestKeys

When to use a variable vs simple value returning function

Why would we use

def table do
  [{?a..?m, :"foo@computer-name"}, {?n..?z, :"bar@computer-name"}]
end

Rather than

table = [{?a..?m, :"foo@computer-name"}, {?n..?z, :"bar@computer-name"}]

In this example

defmodule KV.Router do
  @doc """
  Dispatch the given `mod`, `fun`, `args` request
  to the appropriate node based on the `bucket`.
  """
  def route(bucket, mod, fun, args) do
    # Get the first byte of the binary
    first = :binary.first(bucket)

    # Try to find an entry in the table() or raise
    entry =
      Enum.find(table(), fn {enum, _node} ->
        first in enum
      end) || no_entry_error(bucket)

    # If the entry node is the current node
    if elem(entry, 1) == node() do
      apply(mod, fun, args)
    else
      {KV.RouterTasks, elem(entry, 1)}
      |> Task.Supervisor.async(KV.Router, :route, [bucket, mod, fun, args])
      |> Task.await()
    end
  end

  defp no_entry_error(bucket) do
    raise "could not find entry for #{inspect bucket} in table #{inspect table()}"
  end

  @doc """
  The routing table.
  """
  def table do
    # Replace computer-name with your local machine name
    [{?a..?m, :"foo@computer-name"}, {?n..?z, :"bar@computer-name"}]
  end
end

Taken from docs

Marked As Solved

dimitarvp

dimitarvp

I use functions in these situations to allow myself the liberty to replace a hard-coded constant with a value fetched from a configuration provider – be it plain normal OS environment variables, various secret managers like those found in the Kubernetes ecosystem, AWS-specific secret key-value stores etc.

But, if you are very sure you won’t need to fetch the value from the outside world then you might be better off served by using a module attribute because that makes the code a bit more readable and explicit:

defmodule KV.Router do
  @routing_table [{?a..?m, :"foo@computer-name"}, {?n..?z, :"bar@computer-name"}]

  def route(bucket, mod, fun, args) do
    # ...
    @routing_table |> use_it_here()
    # ...
  end
end

Putting constant values inside your code is a bad idea no matter the programming language. More often than not, you’ll find yourself needing to modify it down the line and then you’ll have trouble finding where did you put it exactly (trust me, we forget where we put stuff all the time). In Elixir, using module attributes clearly expresses your intent as “this is a constant value that I will use one or more times in the code of the module it’s defined in”.

Also Liked

LostKobrakai

LostKobrakai

There’s :math.pi() in erlang.

dimitarvp

dimitarvp

Well, look at your route function above. The table() call blends in perfectly with everything else. Now turn that into an inline variable. Imagine you work actively on something else for 3 months and then come back to this code with the requirement to make that table configurable. Would you immediately remember where you put the hard-coded variable?

Yeah, that’s a bit better, and closer to what I showed you. It’s a good compromise.

davearonson

davearonson

To clarify what I think you mean, inline inside the code with no name to them, such as c = 6.28318530718 * r.

As opposed to putting up top @PI 3.14159265359 (dunno offhand if Elixir provides this but anyway, it could be considered “putting a constant value inside your code”, as it’s in the module) and in the code, c = 2 * @PI * r, or better yet of course circumference = 2 * @PI * radius. That would be perfectly cromulent, in fact generally the recommended way to go.

Would that be a fair interpretation of what you’re trying to say?

dimitarvp

dimitarvp

Yes, that’s what I am saying. Lack of description of what the inline value is supposed to be is a very common problem in most codebases I ever reviewed and participated in.

davearonson

davearonson

Ah, yup. “Magic Numbers”, some folks call it.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

Other popular topics Top

jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement