Hide Utility Class Constructor : Utility classes s

2019-03-08 06:53发布

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.

8条回答
姐就是有狂的资本
2楼-- · 2019-03-08 07:26

make the utility class final and add a private constructor

查看更多
走好不送
3楼-- · 2019-03-08 07:27

If this class is only a utility class, you should make the class final and define a private constructor:

public final class FilePathHelper {

   private FilePathHelper() {
      //not called
   }
}

This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.

查看更多
登录 后发表回答