Hacker News new | ask | show | jobs
by sodapopcan 2086 days ago
I'm on the fence about re-binding variables. I don't really mind it and have gotten used to the pin operator when I need it. I actually use variable re-binding quite a bit but always only in situations where I want a prime.

  def foo(bar) do
    bar = decorate(bar)

    {:ok, bar}
  end
I like that better than calling it something like `new_bar`. I kind of wish there was prime syntax along the lines of `bar' = decorate(bar)` but I can deal with re-binding when only used like this (and really, the stakes are low). More complex cases can generally always be handled with piping.
1 comments

my preference is to only use rebinding if I need to rename something more than once (can happen, in with blocks), and when I do it I postfix-sigil with ! as a code annotation to remind myself to watch out when refactoring the code.

    def foo(bar!) do
      bar! = decorate(bar!)
      bar! = some_more(bar!)
      {:ok, bar!}
    end
Ha! That's a new use of `!` I haven't seen :) But I suppose we are saying completely opposite things. I use rebinding only when I re-bind once. In your example, I would use pipes with a single re-bind:

  def foo(bar) do
    bar =
      bar
      |> decorate()
      |> some_more()

    {:ok, bar}
  end
well, I guess I gave a poor example, suppose you needed to destructure that bar! out of an ok tuple.

    def foo(bar!) do
      with {:ok, bar!} <- thing1(bar!),
           {:ok, bar!} <- thing2(bar!),
           {:ok, bar!} <- thing3(bar!) do
        bar!
      end
    end
Inspiration came from julia, where ! at the end of the function means "watch out, one of the parameters is gonna be mutated!"
Ah ok, I see! I didn't think of this situation. I'm pretty new to the language and only have done hobby projects so I haven't run into this specific scenario. I think here I would just use different names, even if ugly. To me the only "danger" is just in getting confused about what is what. There is otherwise no danger from a memory standpoint since Elixir is immutable. But I can appreciate your use of it here. [edited to add a missing word]
If I get to choose the style, I like doing this...

    bar 
    |> decorate() 
    |> some_more() 
    |> case do 
      result -> 
        {:ok, result} 
    end
I like that. I never occurred to me to pipe into `case`.