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


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

  • 相关阅读:
    模糊匹配
    UPDATE SET FROM WHERE 续
    SQL SERVER 中row_number用法
    临时表和表变量
    镜像
    经典行列转换
    表记录查询最快查询方式
    NULL不是数值
    自增长值
    JSON
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/java-private-constructor.html
Copyright © 2020-2023  润新知