I have always written my if statements like this when I want the negative condition to enter me into the if block.
Example 1
if(condition == false){}
However, we just hired a new senior on the team that insists we should refactor to
Example 2
if(!condition){}
and use that moving forward.
I find example #1 to be easier to reason especially when checking a nested property.
e.g. if(person.name.middle.hasValue == false){}
Question What example is better to practice? or is there a better practice than either example?
Edit Scope
please limit answers to Negative conditions only. of course if(condition == true){} is worst than if(condition){} Because the == true is redundent for the true case but not the false case.
condition == trueis redundant, but== falseis the same as!- if you leave it out, you'll get wrong behaviour. – R. Schmitz Feb 18 '20 at 19:50if(!person.name.middle.hasValue)exactly for what it is. If your find that hard to read, the better solution is to eliminate some of the dots, not tack= falseonto the end of it. – Robert Harvey Feb 18 '20 at 19:51!operator. – πάντα ῥεῖ Feb 18 '20 at 19:52so maybe best is bool missingMiddleName = !person.name.middle.hasValue if(missingMiddleName){}
???
– Luke Hammer Feb 18 '20 at 20:10!person.hasMiddleName? - introduce new method/property in Person class to encapsulate child members. – Fabio Feb 18 '20 at 20:24!and== falseare interchangeable), not redundant (which would mean thatcondition == falseandconditionare exactly the same) – Flater Feb 18 '20 at 20:32ifstatements? – Fabio Feb 19 '20 at 22:07if (false == condition) ..in order to avoid accidental assignments :D – Peter M Feb 20 '20 at 14:50