# Hide Default Constructor In Utility Classes
# Properties
Property | Value |
---|---|
Rule ID | HideDefaultConstructorInUtilityClasses |
First seen in jSparrow version | 3.11.0 |
Minimum Java version | 1.1 |
Remediation cost | 5 min |
Links |
# Description
Utility classes are classes containing static
properties only. Those classes should not be instantiated. A private constructor, which throws an IllegalStateException
, is introduced to utility classes by this rule, if the following criteria are met:
- Only
static
methods and fields are present - No constructor is declared
- No main method is defined
- The default constructor isn't invoked anywhere in the current workspace
This hides the default public constructor and thus prevents the instantiation of such a class.
# Benefits
Prevents the bad practice of unnecessary instatiation of utility classes.
# Code Changes
Pre
public class UtilityClass {
public static void doSomething() {
//...
System.out.println("did something");
}
public static void doSomethingElse() {
//...
System.out.println("did something else");
}
}
Post
public class UtilityClass {
private UtilityClass() {
throw new IllegalStateException("Utility class");
}
public static void doSomething() {
//...
System.out.println("did something");
}
public static void doSomethingElse() {
//...
System.out.println("did something else");
}
}
Automatic Application of This Rule
The automatic application of this rule is supported in the following jSparrow version:
# Tags
1
You & jSparrow