Is there a better way to write conditional structures with Elixir since version1.3

Elixir 1.3 introduces the deprecation of imperative assignments, meaning that a code block similar to:

def modify(state) do
  if some_condition do
    state = modify_my_state(state)
  end

  # some other stuff may happen now here

  state
end

Will produce a warning at compile since state is out of scope. This is understandable. But the suggested solution results in this:

def modify(state) do
  state = if some_condition do
    modify_my_state(state)
  else 
    state
  end

  # some other stuff may happen now here

  state
end

I find it a bit redundant. Is there any other way to make this more clean? Note that the following solution breaks the initial design:

def modify(state) do
  state = if some_condition do
    modify_my_state(state)
  end

  # some other stuff may happen now here

  state
end

Upvotes: 4

Views: 1085

Answers (1)

AbM
AbM

Reputation: 7779

As you mentioned, the redundancy is needed to prevent state from being out of scope.

Making it "cleaner" is just a matter of coding preferences. Here are 2 solutions that come to mind:

  1. Ternary expression

state = if some_condition, do: modify_my_state(state), else: state

  1. Pattern matching of the modifying function:

state = modify_my_state(state, some_condition)

and then pattern match against modify_my_state/2:

defp modify_my_state(state, true), do: modify_my_state(state)
defp modify_my_state(state, false), do: state

Upvotes: 4

Related Questions