When we were working on a Utility class on our Java project. In our project the SonarQube analyze tool was integrated. One of our utility class was called ContentUtils like below:
In the ContentUtil class all our methods was static. It was meant to be for utilities. To access this class methods no instance was needed.
As soon as we analyzed the class the SonarQube it complained with the following error:
Utility classes should not have public constructors
public class ContentUtil {
In the ContentUtil class all our methods was static. It was meant to be for utilities. To access this class methods no instance was needed.
As soon as we analyzed the class the SonarQube it complained with the following error:
Utility classes should not have public constructors
Solution
To fix the issue we had add a private constructor of the utility classprivate ContentUtil() { throw new IllegalStateException("Utility class"); }
Why private constructor
When we use the private constructor Java compiler will not provide a public parameterless constructor. It is also recommended to make the class as final so that other class can't extends this utility class. Final solution is:public final class ContentUtil { private ContentUtil() { throw new IllegalStateException("Utility class"); }
Comments
Post a Comment