rspec/rules/S2059/java/rule.adoc

59 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Serializing a non-``++static++`` inner class will result in an attempt at serializing the outer class as well. If the outer class is actually serializable, then the serialization will succeed but possibly write out far more data than was intended.
Making the inner class ``++static++`` (i.e. "nested") avoids this problem, therefore inner classes should be ``++static++`` if possible. However, you should be aware 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.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public class Raspberry implements Serializable {
// ...
public class Drupelet implements Serializable { // Noncompliant; output may be too large
// ...
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public class Raspberry implements Serializable {
// ...
public static class Drupelet implements Serializable {
// ...
}
}
----
== Resources
2021-04-28 16:49:39 +02:00
* https://wiki.sei.cmu.edu/confluence/x/ZTdGBQ[CERT, SER05-J.] - Do not serialize instances of inner classes
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[]