
## Review A dedicated reviewer checked the rule description successfully for: - [ ] logical errors and incorrect information - [ ] information gaps and missing content - [ ] text style and tone - [ ] PR summary and labels follow [the guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)
59 lines
1.3 KiB
Plaintext
59 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Utility classes, which are collections of `static` members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
|
|
|
|
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
class StringUtils { // Noncompliant
|
|
|
|
public static String concatenate(String s1, String s2) {
|
|
return s1 + s2;
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
class StringUtils { // Compliant
|
|
|
|
private StringUtils() {
|
|
throw new IllegalStateException("Utility class");
|
|
}
|
|
|
|
public static String concatenate(String s1, String s2) {
|
|
return s1 + s2;
|
|
}
|
|
|
|
}
|
|
----
|
|
|
|
=== Exceptions
|
|
|
|
When class contains `public static void main(String[] args)` method it is not considered as utility class and will be ignored by this rule.
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Hide this public constructor.
|
|
|
|
Add a private constructor to hide the implicit public one.
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|