
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
95 lines
2.2 KiB
Plaintext
95 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Singletons that aren't actually singletons become problems instead. To make sure a singleton isn't instantiable, make sure all constructors are ``++private++``. If the singleton doesn't have any constructors then add a ``++private++`` no-args constructor to override the default constructor.
|
|
|
|
|
|
This rule raises an issue when a class that holds a ``++public static final++`` instance of itself has non-``++private++`` constructors or no constructor.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
public class Highlander implements Immortal { // Noncompliant; no constructor; default, public constructor generated
|
|
public static final Highlander INSTANCE = new Highlander();
|
|
|
|
public void eliminateRival(Immortal immortal) {
|
|
// ...
|
|
}
|
|
}
|
|
|
|
public class Kurgan implements Immortal {
|
|
public static final Kurgan INSTANCE = new Kurgan();
|
|
|
|
Kurgan() { // Noncompliant; should be private
|
|
}
|
|
|
|
public void eliminateRival(Immortal immortal) {
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
public class Highlander implements Immortal {
|
|
public static final Highlander INSTANCE = new Highlander;
|
|
|
|
private Highlander() {
|
|
}
|
|
|
|
public void eliminateRival(Immortal immortal) {
|
|
// ...
|
|
}
|
|
}
|
|
|
|
public class Kurgan implements Immortal {
|
|
public static final Kurgan INSTANCE = new Kurgan;
|
|
|
|
private Kurgan() {
|
|
}
|
|
|
|
public void eliminateRival(Immortal immortal) {
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/_zZGBQ[CERT MSC07-J.] - Prevent multiple instantiations of singleton objects
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Make this constructor "private"
|
|
* Add a "private" constructor to this class so the default constructor won't be generated.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== is related to: S1186
|
|
|
|
=== on 11 Jun 2015, 20:07:31 Ann Campbell wrote:
|
|
CodePro: Enforce Singleton Property with Private Constructor
|
|
|
|
=== on 16 Jun 2015, 13:19:32 Nicolas Peru wrote:
|
|
Looks good.
|
|
|
|
=== on 13 Apr 2017, 21:10:24 Ann Campbell wrote:
|
|
We'll probably want to add an exception to the RSPEC-1186 implementation once this rule is implemented
|
|
|
|
endif::env-github,rspecator-view[]
|