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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With