When to invert your if checks
It's not uncommon to see code like this:
if (someCondition is true)
{
// Do a thing
// Do more things
// do a final thing
return result;
}
else
{
return new Failure();
}
Now most people will be quick to spot that we don't need the else, since the IF block returns and we can save a few lines since the if block does an early return
if (someCondition is true)
{
// Do a thing
// Do more things
// do a final thing
return result;
}
return new Failure()
But if we invert our condition we can early return from the else block which is considerable shorter than the if block
if (someCondition is false) return new Failure();
// Do a thing
// Do more things
// do a final thing
return result;
This can be done anytime the blocks result in a method return, and the else block is shorter than the if block. Consider the following function to calculate if a year is a leap year. (A leap year is a year which is divisible by 4, but not 100 unless it's also divisible by 400)
public bool is LeapYear(int year)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
This is the fully written out leap year algorithm with if and else for every condition. Notice that the else blocks all immediately return, and the first two if blocks have more code (the subsequent if blocks). We can apply our inversion rule to clean this up.
if (year % 4 != 0) return false;
if (year % 100 != 0) return true;
if (year % 400 != 0) return false;
return true;
If we replace the boolean expressions with some named extension methods and literals with constants, this code becomes very clear
if (year.IsNotDivisibleBy(4)) return NOT_LEAP_YEAR;
if (year.IsNotDivisibleBy(100)) return LEAP_YEAR;
if (year.IsNotDivisibleBy(400)) return NOT_LEAP_YEAR;
return LEAP_YEAR;