Is it ok to override a variable? Or should I create a new one?

Is there any issue with doing this in Elixir:

def my_method(email) do
    email = String.downcase(email)
    # ...............

It’s not recommended to override variables in such a way, at least in other languages, it has to do with race conditions and there might be other issues as well. And instead I should create a new variable:

def my_method(email) do
    email2 = String.downcase(email)
    # ...............

Also, in Erlang the 1st example won’t work.

It is a common idiom to rebind a single variable multiple times as long as it is the same thing as before.

1 Like

No, you can override variable without any concerns, but remember that this is actually rebindng.

Elixir is also immutable language and variables are just a labels for values you want to name.
There’s beauty in Elixir that whenever you will pass this value into next function as a first argument, you can do this:

 a
 |> func1()
 |> func2()
 |> func3()

which is equal to

func3(func2(func1(a)))

This is the reason people use different variables in different languages - to make the code more readable. In Elixir you don’t have to do that. Also, if you don’t need to return some value explicitly, you don’t need to change the binding as well.

In your example - assuming that you won’t return email, because your method (should be function) will do something eg. validate it against DB whether this email is already used, you would do something like that:

def validate_uniqueness(email) do
  email
  |> String.downcase()
  |> is_already_in_db?() # this private function would do something like Repo.get_by(User, email: email)
end

TL;DR: Rebinding variables is normal thing and don’t be afraid to do that :slight_smile:

3 Likes