Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert "if" statement to reduce nesting

Tags:

c#

resharper

When I ran ReSharper on my code, for example:

    if (some condition)     {         Some code...                 } 

ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:

   if (!some condition) return;    Some code... 

I would like to understand why that's better. I always thought that using "return" in the middle of a method problematic, somewhat like "goto".

like image 948
Lea Cohen Avatar asked Nov 06 '08 09:11

Lea Cohen


People also ask

Why invert if statement to reduce nesting?

It is not only aesthetic, but it also reduces the maximum nesting level inside the method. This is generally regarded as a plus because it makes methods easier to understand (and indeed, many static analysis tools provide a measure of this as one of the indicators of code quality).

How do you reverse an if statement in Python?

Position the caret over an if-else statement. Press Alt+Enter. From the pop-up menu, select Invert if-else statement.


1 Answers

It is not only aesthetic, but it also reduces the maximum nesting level inside the method. This is generally regarded as a plus because it makes methods easier to understand (and indeed, many static analysis tools provide a measure of this as one of the indicators of code quality).

On the other hand, it also makes your method have multiple exit points, something that another group of people believes is a no-no.

Personally, I agree with ReSharper and the first group (in a language that has exceptions I find it silly to discuss "multiple exit points"; almost anything can throw, so there are numerous potential exit points in all methods).

Regarding performance: both versions should be equivalent (if not at the IL level, then certainly after the jitter is through with the code) in every language. Theoretically this depends on the compiler, but practically any widely used compiler of today is capable of handling much more advanced cases of code optimization than this.

like image 178
Jon Avatar answered Sep 19 '22 12:09

Jon