rspec/rules/S1118/java/rule.adoc

45 lines
1.1 KiB
Plaintext
Raw Normal View History

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.
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:47:33 +02:00
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
----
class StringUtils { // Noncompliant
public static String concatenate(String s1, String s2) {
return s1 + s2;
}
}
----
== Compliant Solution
----
class StringUtils { // Compliant
private StringUtils() {
throw new IllegalStateException("Utility class");
}
public static String concatenate(String s1, String s2) {
return s1 + s2;
}
}
----
== Exceptions
2021-01-27 13:42:22 +01:00
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[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]