隐藏实用程序类构造函数:实用程序类不应具有公共或默认构造函数 [英] Hide Utility Class Constructor : Utility classes should not have a public or default constructor
问题描述
我在Sonar上收到这个警告。我想要解决方案删除声纳上的这个警告。
我的类是这样的:
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.
推荐答案
如果这个类只是一个实用类,你应该使类final,并定义一个私有构造函数:
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
}
}
这可以防止默认的无参数构造函数在代码中的其他位置被使用。另外,你可以使类final,以便它不能在子类中扩展,这是实用程序类的最佳实践。因为你只声明了一个私有的构造函数,其他类不能扩展它,但它仍然是一个最佳实践,将该类标记为final。
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.
这篇关于隐藏实用程序类构造函数:实用程序类不应具有公共或默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!