This is a minor style question, but every bit of readability you add to your code counts.
So if you've got:
if (condition) then
{
// do stuff
}
else
{
// do other stuff
}
How do you decide if it's better like that, or like this:
if (!condition) then
{
// do other stuff
{
else
{
// do stuff
}
My heuristics are:
- Keep the condition positive (less mental calculation when reading it)
- Put the most common path into the first block
For me it depends on the condition, for example:
I tend to talk to my self with what I want the logic to be and code it to the little voice in my head.
If the code is to check for an error condition, I prefer to put that code first, and the "successful" code second; conceptually, this keeps a function call and its error-checking code together, which makes sense to me because they are related. For example:
It depends on your flow. For many functions, I'll use preconditions:
If I need to do something each case, I'll use an
if (positive_clause) {} else {}
format.When I am looking at data validation, I try to make my conditions "white listing" - that is, I test for what I will accept:
Rather than the other way around, which tends to degenerate into:
If one of the two paths is very short (1 to 10 lines or so) and the other is much longer, I follow the Holub rule mentioned here and put the shorter piece of code in the if. That makes it easier to see the if/else flow on one screen when reviewing the code.
If that is not possible, then I structure to make the condition as simple as possible.
I agree with Oli on using a positive if clause when possible.
Just please never do this:
I used to see this a lot at one place I worked and used to wonder if one of the coders didn't understand how not works...