[java] Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I am getting this warning on Sonar.I want solution to remove this warning on sonar. My class is like this :

public class FilePathHelper {
    private static String resourcesPath;

    public static String getFilePath(HttpServletRequest request) {
        if(resourcesPath == null) {
            String serverpath=request.getSession().getServletContext().getRealPath("");             
            resourcesPath = serverpath + "/WEB-INF/classes/";   
        }
        return resourcesPath;       
    }
}

i want proper solution to remove this warning on sonar.

This question is related to java constructor sonarqube

The answer is


I use an enum with no instances

public enum MyUtils { 
    ; // no instances
    // class is final and the constructor is private

    public static int myUtilityMethod(int x) {
        return x * x;
    }
}

you can call this using

int y = MyUtils.myUtilityMethod(5); // returns 25.

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.


make the utility class final and add a private constructor


I don't know Sonar, but I suspect it's looking for a private constructor:

private FilePathHelper() {
    // No-op; won't be called
}

Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.

(You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)


I recommend just disabling this rule in Sonar, there is no real benefit of introducing a private constructor, just redundant characters in your codebase other people need to read and computer needs to store and process.


Add private constructor:

private FilePathHelper(){
    super();
}

Best practice is to throw an error if the class is constructed.

Example:

/**
 * The Class FooUtilityService.
 */
final class FooUtilityService{

/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {

    // Throw an exception if this ever *is* called
    throw new AssertionError("Instantiating utility class.");
}

You can just use Lombok with access level PRIVATE in @NoArgsConstructor annotation to avoid unnecessary initialization.

@NoArgsConstructor(access = AccessLevel.PRIVATE)

public class FilePathHelper {

// your code

}


SonarQube documentation recommends adding static keyword to the class declaration.

That is, change public class FilePathHelper to public static class FilePathHelper.

Alternatively you can add a private or protected constructor.

public class FilePathHelper
{
    // private or protected constructor
    // because all public fields and methods are static
    private FilePathHelper() {
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to constructor

Two constructors Class constructor type in typescript? ReactJS: Warning: setState(...): Cannot update during an existing state transition Inheritance with base class constructor with parameters What is the difference between using constructor vs getInitialState in React / React Native? Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor Call asynchronous method in constructor? Purpose of a constructor in Java? __init__() missing 1 required positional argument

Examples related to sonarqube

ERROR: Sonar server 'http://localhost:9000' can not be reached SonarQube not picking up Unit Test Coverage Sonar properties files SonarQube Exclude a directory Hide Utility Class Constructor : Utility classes should not have a public or default constructor How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report? How to make Sonar ignore some classes for codeCoverage metric? Turning Sonar off for certain code