Closed wnagrodzki closed 6 years ago
@pwgr Do you have any comments on that guideline? Michał and I think this would be useful to add.
That’s reasonable, I would also expand this with a recommendation against using “negative” names for boolean variables/properties, e.g. name the variable “isAvailable” instead of “unavailable”.
The above matters when a variable is used with ?: operator - placing the “main” flow in the first segment (before the semicolon) usually feels more natural, I’m doing it even if it forces me to negate the test.
@pwetrifork Good point, I also prefer "positive" variable/property names as I experience mental tax when reading "negative" ones.
However, if I were to choose from the examples below I would use the second one.
let light = !resource.unavailable ? .green : .red
let light = resource.unavailable ? .red : .green
Did I understand you correctly that you would prefer to use the first option?
There is no clear “main” path in the example above, what I meant were cases like returning nil from the test. In such situation I would avoid placing the nil segment first.
@pwetrifork Could you provide an example?
return unavailable ? nil : someOperationOnAvailable() vs return !unavailable ? someOperationOnAvailable() : nil
Here I would prefer the second option when it comes to ?: operator segments arrangement. That’s why I mentioned the whole positive vs negative boolean naming thing.
@pwetrifork Good point, I like that idea
@pwetrifork @Moskacz Would you consider the section good enough to become the guideline? Maybe we should change the title, but I do not have any better propositions now.
Looks good for me, I'd just remove parentheses from examples that have if
statement
Do not use negative conditions with guard.
Guard statement often forces you to use negation, and at the same time it's better than if for early returns - it's not possible to miss a return/throw/etc. statement.
This is a very good point. I am leaning towards using if
as potential mistakes should be caught by unit tests.
Don't not avoid double negation.
Use "positive" names for variables and properties.
Do not use negative conditions with guard.
Source: Uncle Bob, Mattt