Friday, June 29, 2007

Be Positive

No, I don't mean in a cheesy Disney way. I mean in a nerdy boolean logic way. I'm not sure where I picked up this rule of thumb, but one particularly subtle bit of .NET developer guidance I've started to try to follow is to keep booleans positive. For example: if (myPerson.IsActive) ... //"if the person is active". is easier to think through than: if (! myPerson.IsInactive) ... //"if the person is not inactive". At first pass, this seems nitpicky and maybe even arbitrary. Doesn't this rule just make it longer to test for a negative? if (! myPerson.IsActive) ... But the point isn't so much the amount of code, as it is the the double-negative "not inactive", which burns a few more brain cells to get. An extension of this is when branching: if (myPerson.IsActive) doSomething(); else doSomethingElse(); is better than if (!myPerson.IsActive) doSomethingElse; else doSomething(); Again, the reason isn't so much for the one if..then..else, as it is for the consistency and readability of code as a whole. Anyway, it's helped me =)

No comments: