티스토리 뷰

"Add a private constructor to hide the implicit public one."

유틸 클래스에서는 public 생성자가 없어야 합니다. 

유틸 클래스 만들 때는 private 생성자를 추가해 주세요. 


public class ValidatorUtil {

    private ValidatorUtil() {

        throw new IllegalStateException("Utility class");

    }

...

}

 

Utility classes should not have public constructors (squid:S1118)

CODE_SMELL Code smell MAJOR Major

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.

Noncompliant Code Example

class StringUtils { // Noncompliant

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

}

Compliant Solution

class StringUtils { // Compliant

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

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

}

Exceptions

When class contains public static void main(String[] args) method it is not considered as utility class and will be ignored by this rule.



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함