rspec/rules/S2694/java/rule.adoc

67 lines
1.8 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
A non-static inner class has a reference to its outer class, and access to the outer class' fields and methods. That class reference makes the inner class larger and could cause the outer class instance to live in memory longer than necessary.
If the reference to the outer class isn't used, it is more efficient to make the inner class ``++static++`` (also called nested). If the reference is used only in the class constructor, then explicitly pass a class reference to the constructor. If the inner class is anonymous, it will also be necessary to name it.
However, while a nested/``++static++`` class would be more efficient, it's worth noting that there are semantic differences between an inner class and a nested one:
* 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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public class Fruit {
// ...
public class Seed { // Noncompliant; there's no use of the outer class reference so make it static
int germinationDays = 0;
public Seed(int germinationDays) {
this.germinationDays = germinationDays;
}
public int getGerminationDays() {
return germinationDays;
}
}
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public class Fruit {
// ...
public static class Seed {
int germinationDays = 0;
public Seed(int germinationDays) {
this.germinationDays = germinationDays;
}
public int getGerminationDays() {
return germinationDays;
}
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]