Effective Java's own interpretation. I tried to interpret item 4 of the 3rd edition by writing my own code.
For classes that have only static members, provide a private constructor that raises a runtime exception.
For example, a utility class that collects only common processes (hereinafter referred to as Util class) has only static methods and static variables, and is not premised on instantiation.
In general, public Util class has a public default constructor unless a constructor is defined, so there is a concern that it will be unnecessarily instantiated in an external class.
By explicitly defining a private constructor, you can prevent constructor calls outside the Util class. Also, by putting exception output processing in the constructor, it is possible to make the constructor call in the Util class an error.
** Util class **
public class SampleUtil {
public static final String HOGE = "hoge";
public static String fugaMethod() {
return "fuga";
}
}
** Caller class **
public class SampleService {
public String sampleMethod() {
//Uselessly instantiated
SampleUtil sampleUtil = new SampleUtil();
return sampleUtil.fugaMethod();
}
}
I am creating an instance in the calling class. Since fugaMethod ()
is a static method, it is useless to instantiate it.
** Util class **
public class SampleUtil {
//Define a constructor that is private and outputs a runtime exception
private SampleUtil() {
throw new IllegalStateException("Util instance construction is not allowed.");
}
public static final String HOGE = "hoge";
public static String fugaMethod() {
return "fuga";
}
}
** Caller class **
public class SampleService {
public String sampleMethod() {
return SampleUtil.fugaMethod();
}
}
Since the constructor is private, it cannot be instantiated in another class in the first place.
Also, even if the constructor is called in the Util class, an exception will be output and no instance will be created. If you have code that calls the constructor, it's a programming error, so be sure to throw a runtime exception.
Recommended Posts