rspec/rules/S1199/java/rule.adoc

76 lines
1.5 KiB
Plaintext
Raw Normal View History

== 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]