Modify rule S2694: Add code example for local classes (#3748)

This commit is contained in:
Angelo Buono 2024-03-08 12:05:57 +01:00 committed by GitHub
parent d17c91715e
commit 0eff2938a4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -11,10 +11,21 @@ However, while a nested/``++static++`` class would be more efficient, it's worth
* an inner class can only be instantiated within the context of an instance of the outer class.
* a nested (``++static++``) class can be instantiated independently of the outer class.
== How to fix it
=== Noncompliant code example
There are two scenarios in which this rule will raise an issue:
[source,java]
1. On an _inner class_: make it `static`.
2. On a _local class_: extract it as a `static` _inner class_.
=== Code examples
==== Noncompliant code example
Inner classes that don't use the outer class reference should be static.
[source,java,diff-id=1,diff-type=noncompliant]
----
public class Fruit {
// ...
@ -31,10 +42,9 @@ public class Fruit {
}
----
==== Compliant solution
=== Compliant solution
[source,java]
[source,java,diff-id=1,diff-type=compliant]
----
public class Fruit {
// ...
@ -51,6 +61,70 @@ public class Fruit {
}
----
Local classes that don't use the outer class reference should be extracted as a static inner classes.
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
public class Foo {
public Foo() {
class Bar { // Noncompliant
void doSomething() {
// ...
}
}
new Bar().doSomething();
}
public void method() {
class Baz { // Noncompliant
void doSomething() {
// ...
}
}
new Baz().doSomething();
}
}
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
public class Foo {
public Foo() {
new Bar().doSomething();
}
public void method() {
new Baz().doSomething();
}
private static class Bar { // Compliant
void doSomething() {
// ...
}
}
private static class Baz { // Compliant
void doSomething() {
// ...
}
}
}
----
== Resources
=== Documentation
* https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html[Oracle Java SE - Nested Classes]
* https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html[Oracle Java SE - Local Classes]
=== Articles & blog posts
* https://www.geeksforgeeks.org/difference-between-static-and-non-static-nested-class-in-java/[GeeksforGeeks - Difference between static and non-static nested class in Java]
ifdef::env-github,rspecator-view[]