75 lines
1.2 KiB
Plaintext
75 lines
1.2 KiB
Plaintext
Conditional execution increases code nesting and decreases readability. When the body of a method or loop ends with code that is conditionally executed, it can be simplified by inverting the condition with a ``++continue++`` or early ``++return++``.
|
|
|
|
|
|
This rule raises an issue when a method or loop ends with a conditional block containing at least two statements.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,text]
|
|
----
|
|
public void conditionalMethod()
|
|
{
|
|
if (condition) // Noncompliant
|
|
{
|
|
doFirstThing();
|
|
doSecondThing();
|
|
doThirdThing();
|
|
}
|
|
}
|
|
|
|
public void conditionalLoop()
|
|
{
|
|
for(int i = 0; i < 10; i++)
|
|
{
|
|
if (condition) // Noncompliant
|
|
{
|
|
doTheThing();
|
|
doTheOtherThing();
|
|
}
|
|
}
|
|
|
|
if (otherCondition) // Compliant
|
|
{
|
|
doTheFinalThing();
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,text]
|
|
----
|
|
public void conditionalMethod()
|
|
{
|
|
if (!condition)
|
|
{
|
|
return;
|
|
}
|
|
doFirstThing();
|
|
doSecondThing();
|
|
doThirdThing();
|
|
}
|
|
|
|
public void conditionalLoop()
|
|
{
|
|
for(int i = 0; i < 10; i++)
|
|
{
|
|
if (!condition)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
doTheThing();
|
|
doTheOtherThing();
|
|
}
|
|
|
|
if (otherCondition)
|
|
{
|
|
doTheFinalThing();
|
|
}
|
|
}
|
|
----
|
|
|