During code review I discovered many places of our C# code that looks like this:
if(IsValid()) {
return true;
}
else {
return false;
}
<
First case is easier when you are debugging. When you step through your source, it is easier to find out what the return value is without opening up immediate window
or run IsValid();
just to see the return value.
For the first and second case, developer might not be aware that s/he can simply do
return IsValid();
Lastly, a developer might be forced to use first or second syntax due to company policies.
The reasons for the first two examples are entirely human:
There's no reason not to (I know it's a double negative) go with return IsValid();
If you're absent-minded, it's easy to refactor some code from this:
private bool ConsiderTheOstrich()
{
/* do ostrich things */
if(someCondition && unpredictableThing == 5)
return true;
else
{
// log something
return false;
}
}
To this:
private void IsValid() { return (someCondition && unpredictableThing == 5); }
/* ... */
private void ConsiderTheOstrich()
{
/* do ostrich things */
if(IsValid())
return true;
else
return false; // ostrichlogger logs it for us now
}
Without noticing the extra opportunity for brevity.
Yes, of course return IsValid();
would be most optimal if the only code you have is as above.
I guess what comes into play though is what else is your function doing? The rest of the code might shed more light on why a developer would put an if statement around IsValid().
After all, if it's just returning IsValid() then why isn't the calling code just checking IsValid() directly rather than having this wrapper method.
I would also just say "return IsValid();" I think you're 100% correct in doing so
return IsValid();
is the way to go. less code, more concise - choice of champions