org.sonar.plugins.csharp.S1199.html Maven / Gradle / Ivy
Why is this an issue?
Nested code blocks create new scopes where variables declared within are inaccessible from the outside, and their lifespan ends with the block.
Although this may appear beneficial, their usage within a function often suggests that the function is overloaded. Thus, it may violate the Single
Responsibility Principle, and the function needs to be broken down into smaller functions.
The presence of nested blocks that don’t affect the control flow might suggest possible mistakes in the code.
Exceptions
The usage of a code block after a case
is allowed.
How to fix it
The nested code blocks should be extracted into separate methods.
Code examples
Noncompliant code example
public void Evaluate()
{
/* ... */
{ // Noncompliant - nested code block '{' ... '}'
int a = stack.pop();
int b = stack.pop();
int result = a + b;
stack.push(result);
}
/* ... */
}
Compliant solution
public void Evaluate()
{
/* ... */
StackAdd();
/* ... */
}
private void StackAdd()
{
int a = stack.pop();
int b = stack.pop();
int result = a + b;
stack.push(result);
}
Resources
Documentation
- Wikipedia - Single Responsibility Principle
© 2015 - 2024 Weber Informatics LLC | Privacy Policy