Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is assignment from control flow (ifs, switches) good style?

I've seen a lot of code written like this;

conditional_value = if thing_is_true
                      true_value
                    else
                      other_value
                    end

I feel conflicted about this. On one hand it's nice to use the return value of the conditional (or any other syntactic chunk like switches, begin/ends, loops, or even function definitions) to reduce redundancy and make it clear what the code is doing. On the other hand, the indentation is often jarring and confusing.

As a second possibility, if one decides to have all lines indented to the level of the beginning of the first line, that destroys the visual cue of the whole structure.

conditional_value = if thing_is_true
  true_value
else
  other_value
end

Here's a third alternative (at least in Ruby) relying on line breaks;

conditional_value =
  if thing_is_true
    true_value
  else
    other_value
  end

A fourth alternative is to bite the bullet and put the assignment statement in every branch.

if thing_is_true
  conditional_value = true_value
else
  conditional_value = other_value
end

I'm wary of this becoming an 'opinions' question, but I think there are facts I don't know;

  • How often are these styles seen in professional code?
  • How easy is it for people to read?
  • Do any of these styles commonly cause bugs?
  • In what ways do these styles maintain or break the integrity of the visual presentation of the code?
like image 851
Alex Altair Avatar asked Jan 18 '26 13:01

Alex Altair


1 Answers

I would only assign the result of a ternary operator val = condition ? true_value: false_value, not the value of an if expression. This may just be a habit from Java/C/C++, but using if this way does seem to potentially confuse flow control with expression value. Your fourth alternative above would be OK in this style.

But if you have a consistent style that includes using the value of if, it's fine, too.

like image 69
Joshua Fox Avatar answered Jan 21 '26 06:01

Joshua Fox