rspec/rules/S1199/java/rule.adoc
Angelo Buono c24d13b88a
Modify S1199: Migrate to LayC - Nested code blocks should not be used (#3233)
Co-authored-by: Marco Borgeaud <89914223+marco-antognini-sonarsource@users.noreply.github.com>
2023-10-11 06:59:57 +00:00

76 lines
1.5 KiB
Plaintext

== Why is this an issue?
include::../description.adoc[]
=== 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
[source,java,diff-id=1,diff-type=noncompliant]
----
class Example {
private final Deque<Integer> stack = new LinkedList<>();
public void evaluate(int operator) {
switch (operator) {
case ADD: {
/* ... */
{ // Noncompliant - Extract this nested code block into a method
int a = stack.pop();
int b = stack.pop();
int result = a + b;
stack.push(result);
}
/* ... */
break;
}
/* ... */
}
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
class Example {
private final Deque<Integer> stack = new LinkedList<>();
public void evaluate(int operator) {
switch (operator) {
case ADD: {
/* ... */
evaluateAdd();
/* ... */
break;
}
/* ... */
}
}
private void evaluateAdd() {
int a = stack.pop();
int b = stack.pop();
int result = a + b;
stack.push(result);
}
}
----
== Resources
=== Documentation
* Wikipedia - https://en.wikipedia.org/wiki/Single-responsibility_principle[Single Responsibility Principle]
* Baeldung - https://www.baeldung.com/java-single-responsibility-principle[Single Responsibility Principle]