Utility Class Should Have Private Constructor
ID |
java.utility_class_private_constructor |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style |
Description
Reports utility classes (classes containing only static methods and static fields) that do not declare a private no-arg constructor. Without it, the class can be accidentally instantiated or subclassed.
Rationale
A utility class is a container for static helper methods and should never be instantiated. Java provides a default public no-arg constructor if no constructor is declared, which allows new UtilityClass() and subclassing. Declaring a private no-arg constructor prevents both.
// Bad -- utility class without private constructor
public class StringUtils {
public static boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
}
// Good -- private constructor prevents instantiation
public class StringUtils {
private StringUtils() {}
public static boolean isEmpty(String s) {
return s == null || s.length() == 0;
}
}