3 ms·
Agreed again. Also, the longer I write code the more I find myself avoiding anything but single-line if/unless statement modifiers. And I avoid if/else in almo
by stouset 6y ago
Agreed again.
Also, the longer I write code the more I find myself avoiding anything but single-line if/unless statement modifiers. And I avoid if/else in almost all scenarios.
For the first situation, most `if` branches fall into two categories: guard statements, or genuine branching logic. For the former, guard statement style greatly improves clarity and you only need the statement modifier form. For the latter, I find in almost all cases you either should be writing two methods (one for the true case, one for the false case), or the inner logic of the `if` should simply be its own method.
return nil if thing?
return true unless other_thing?
logic()
special_situation if
another_thing?
logic2()
That just reads significantly easier to me than anything involving nested conditional logic. This isn't always the case, but it is often enough that I write a block-style `if` less than once a month.
For `if`/`else`, I avoid them at all costs. If there's exactly two cases, odds are I probably want to separate methods (and can write a short method that chooses between the two if necessary). In almost all other cases, I'd infinitely rather prefer a `case` statement that can use tabular alignment for clarity.
case foo
when bar then baz
when ham then spam
else qux
end
That's way easier to parse visually than if/else/elsif/elsif/else blocks. Plus it makes sure that I keep absolutely minimal logic inside of the branched cases, and never have nested branching.
- dragonwriter 6y ago> I'd infinitely rather prefer a `case` statement Generally, yes. > that can use tabular alignment for clarity. I hate you. I mean, not you personally, but please don't. Even when I'm using a monospaced font, that vast gulf of whitespace between the else keyword and the substance of the else clause kills readability, and since I actually now pretty consistently use proportional fonts for programming... (I mean, sure, if its an environment where you now elastic tabstops are available, tabular alignment is fine; if you're faking it with spaces, though...)