Code Issues – Nested code can be flattened
This CodeRush code issue shows a hint (suggestion) when the nested code structure can be simplified and unintended. This is allowed by converting conditional statements into a guard clauses:
void Method()
{
if (condition1)
{
if (condition2)
{
if (condition3)
{
// code goes here...
}
}
}
}
Result:
void Method()
{
if (!condition1) return;
if (!condition2) return;
if (!condition3) return;
// code goes here...
}
The practical reason for this is that it simplifies your reading of the code and reduces the apparent complexity. There is no specific limit for the amount of nested code blocks, however, if you get your code nested too deep, most likely, it must be refactored. In some cases, it’s better to validate all of your input conditions at the beginning of a method and just bail out if anything is not correct. This follows the “fail fast” principle, and you really start to notice the benefit when you have lots of conditions. You can have a series of single-level if-statement checks that check successively more and more specific things, until you’re confident that your inputs are correct. The rest of the method will then be much easier to write and follow, and will tend to have fewer nested conditionals.
The fixing provider for this code issue is the Flatten Conditional refactoring.
—– Products: CodeRush Pro Versions: 10.2 and up VS IDEs: any Updated: Mar/23/2011 ID: C074
what about this :
void Method()
{
boolean test = condition1 && condition2 && condition3;
if (!test) return;
// code goes here…
}
@ uranus
This code is already flattened, there are no nested conditionals, so there is nothing to change.