Is there a better way to write conditional structures with Elixir from version 1.3

Elixir 1.3 introduces obsolescence of peremptory assignments, which means the code block is 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

A warning will be issued during compilation, as it stateis beyond the scope. This is clear. But the proposed solution leads to the following:

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 little redundant. Is there any other way to make this cleaner? Please note that the following solution violates the original design:

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

  # some other stuff may happen now here

  state
end
+4
source share
1 answer

As you mentioned, redundancy is needed to prevent statedue to inaccessibility.

Making it cleaner is just a coding issue. Here are two solutions that come to mind:

  • Ternic expression

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

  1. :

state = modify_my_state(state, some_condition)

modify_my_state/2:

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

All Articles