公用的工具類不應該有公共的構造函數


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