From 0eff2938a49e4a20bde484c8f110b8483dee4c01 Mon Sep 17 00:00:00 2001 From: Angelo Buono Date: Fri, 8 Mar 2024 12:05:57 +0100 Subject: [PATCH] Modify rule S2694: Add code example for local classes (#3748) --- rules/S2694/java/rule.adoc | 84 +++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/rules/S2694/java/rule.adoc b/rules/S2694/java/rule.adoc index c07157b612..31071e6638 100644 --- a/rules/S2694/java/rule.adoc +++ b/rules/S2694/java/rule.adoc @@ -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[]