公用的工具类不应该有公共的构造函数


Sonarlint检测出如下问题:

Utility classes should not have public constructors

  Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
  Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.


公用的工具类不应该有公共的构造函数

公用的工具类是静态成员的集合,并不意味着要实例化。甚至扩展的抽象工具程序类也不应该有公共构造函数。

Java会向不定义构造函数的每个类添加隐式的公共构造函数。因此,应该定义至少一个非公共构造函数。


错误代码示例:

class StringUtils { // Noncompliant      
    public static String concatenate(String s1, String s2) {
        return s1 + s2;
    }
}

 

正确代码示例:

class StringUtils { // Compliant    

    private StringUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static String concatenate(String s1, String s2) {
        return s1 + s2;
    }
}

  

例外情况:

当类包含 public static void main(String[] args) 方法时,它不被视为工具类类,并且将被该规则忽略。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM