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.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...)
The point of stating an explicit nil in the article must be to reduce the chance of future changes erroneously leaving something on the stack, without realizing the implicit nil.
The early return in your version makes it much more obvious why it is written the way it is.
class SanitizingFilter < HTMLFilter
def render_element(name, attrs, content)
safe?(name, attrs) ? super : nil
end
end
Maybe I find it easier because I started programming with Basic and based a lot of logic on GOTO line and then moved to assembler language where again it used JMP so I represent code with nodes and edges in my mind.
Also, the original code - which the author prefers - has a positive ratio of language keywords over content (or logic) i.e extra 'end' and 'else' which does not bring too much information and makes me read it twice just to be sure I did not missed anything.