2023-05-03 11:06:20 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
2021-04-26 17:29:13 +02:00
|
|
|
include::../description.adoc[]
|
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
=== Exceptions
|
2021-04-26 17:29:13 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
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
|
2021-04-26 17:29:13 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
==== Noncompliant code example
|
2021-04-26 17:29:13 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
2021-04-26 17:29:13 +02:00
|
|
|
----
|
2023-10-11 08:59:57 +02:00
|
|
|
class Example {
|
|
|
|
|
|
|
|
private final Deque<Integer> stack = new LinkedList<>();
|
2021-04-26 17:29:13 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
/* ... */
|
|
|
|
}
|
|
|
|
}
|
2021-04-26 17:29:13 +02:00
|
|
|
}
|
|
|
|
----
|
2021-06-02 20:44:38 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
|
|
----
|
|
|
|
class Example {
|
2021-09-20 15:38:42 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
private final Deque<Integer> stack = new LinkedList<>();
|
2021-09-20 15:38:42 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
public void evaluate(int operator) {
|
|
|
|
switch (operator) {
|
|
|
|
case ADD: {
|
|
|
|
/* ... */
|
|
|
|
evaluateAdd();
|
|
|
|
/* ... */
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
/* ... */
|
|
|
|
}
|
|
|
|
}
|
2021-09-20 15:38:42 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
private void evaluateAdd() {
|
|
|
|
int a = stack.pop();
|
|
|
|
int b = stack.pop();
|
|
|
|
int result = a + b;
|
|
|
|
stack.push(result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
2021-06-02 20:44:38 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
== Resources
|
2023-06-22 10:38:01 +02:00
|
|
|
|
2023-10-11 08:59:57 +02:00
|
|
|
=== 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]
|