3

Resharper (or is it Visual Studio - it's a yellow light bulb with a tiny red filament in it) offers to "invert if" on this code:

if (tItems >= 0)
{
    return tItems;
}
SetTotalItemsAndTotalAmt();

...and if I allow it to, it becomes this:

if (tItems < 0)
{
    SetTotalItemsAndTotalAmt();
}
return tItems;

...but then it offers to "invert if" again, and if I gullibly take the bait, it sets it back to its former glory.

If one way is considered better (more grokkable, I guess) than the other, why would it also allow a reverse inversion? And if it's a case of "six of one and half a dozen of the other," why does it even bother to offer a change?

UPDATE

Actually, come to think of it, one of those ways is not even valid, for it says, "WorkFiles.getAmount()': not all code paths return a value" unless it has the return statement outside the if condition.

My guess is this is not Resharper doing this; those Urquell-powered cats wouldn't do such a thing, methinks.

1 Answers1

4

It's ReSharper that's offering this, and it offers it because it can. There can be many good reasons to let it do so. I frequently use this when refactoring code like:

if (cond1) {
   if (cond2) {
      if (cond3) {
         DoSomething();
      } else {
         throw "Error 3";
      }
   } else {
      throw "Error 2";
   }
} else {
   throw "Error 1";
}
return;

into:

if (!cond1) throw "Error 1";
if (!cond2) throw "Error 2";
if (!cond3) throw "Error 3";
DoSomething();
return;

It's especially useful when those ifs run on for several screens of code. And yes, I see code like this often.

Ross Patterson
  • 10,277
  • 34
  • 43
  • 1
    So it's just that sometimes Resharper offers a refactor that doesn't add substantial value. – Robert Harvey Aug 30 '13 at 00:15
  • Not "doesn't add substantial value", but rather "is not a good or bad thing, but is a thing that might be troublesome to do without a single-button implementation." – Ross Patterson Aug 30 '13 at 18:38
  • I usually add ignore comments if Resharper annoys me with flipping an easy to understand positive condition into a weird negative on. In your example it makes sense but there are many scenarios where it's not really helpful. – t3chb0t Mar 31 '18 at 20:08