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
I always keep the most likely first.
In Perl I have an extra control structure to help with that. The inverse of if.
I think that for a single variable the not operator is simple enough and naming issues start being more relevant.
Never name a variable not_X, if in need use a thesaurus and find an opposite. I've seen plenty of awful code like
instead of the obvious
Then you can sanely use (very readable, no need to invert the code blocks)
If we're talking about more variables I think the best rule is to simplify the condition. After a while projects tend to get conditions like:
Which translates to
Always pay attention to what conditions look like and how to simplify them.
If you have both true and false conditions then I'd opt for a positive conditional - This reduces confusion and in general I believe makes your code easier to read.
On the other hand, if you're using a language such as Perl, and particularly if your false condition is either an error condition or the most common condition, you can use the 'unless' structure, which executes the code block unless the condition is true (i.e. the opposite of if):
You should always put the most likely case first. Besides being more readable, it is faster. This also applies to switch statements.
Software is knowledge capture. You're encoding someone's knowledge of how to do something.
The software should fit what's "natural" for the problem. When in doubt, ask someone else and see what people actually say and do.
What about the situation where the "common" case is do nothing? What then
Or do you do this?
The "always positive" rule isn't really what you want first. You want to look at rules more like the following.
You can usually make the condition positive without switching around the if / else blocks.
Change
to