zoukankan      html  css  js  c++  java
  • 公用的工具类不应该有公共的构造函数

    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) 方法时,它不被视为工具类类,并且将被该规则忽略。

  • 相关阅读:
    Yii2 分页
    Yii2 或者当前登录用户帐号
    css3媒体查询判断移动设备横竖屏
    Javascript操作Tr隐藏显示变形~
    php注释标准
    匹配一段html中所有的src
    数据库遇到错误(随时补充)
    NetCore-缓存文件上传和文件流上传
    SVN跨服务器版本迁移
    发票同步微信卡包
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/java-private-constructor.html
Copyright © 2011-2022 走看看