developer tip

유틸리티 클래스 생성자 숨기기 : 유틸리티 클래스에는 공용 또는 기본 생성자가 없어야합니다.

copycodes 2020. 9. 18. 08:19
반응형

유틸리티 클래스 생성자 숨기기 : 유틸리티 클래스에는 공용 또는 기본 생성자가 없어야합니다.


Sonar에서이 경고를 받고 있습니다. Sonar에서이 경고를 제거하는 솔루션을 원합니다. 내 수업은 다음과 같습니다.

public class FilePathHelper {
    private static String resourcesPath;

    public static String getFilePath(HttpServletRequest request) {
        if(resourcesPath == null) {
            String serverpath=request.getSession().getServletContext().getRealPath("");             
            resourcesPath = serverpath + "/WEB-INF/classes/";   
        }
        return resourcesPath;       
    }
}

소나에서이 경고를 제거하는 적절한 솔루션을 원합니다.


이 클래스가 유틸리티 클래스 일 경우 클래스를 final로 만들고 전용 생성자를 정의해야합니다.

public final class FilePathHelper {

   private FilePathHelper() {
      //not called
   }
}

이렇게하면 매개 변수가없는 기본 생성자가 코드의 다른 곳에서 사용되지 않습니다. 또한 클래스를 최종적으로 만들 수 있으므로 하위 클래스에서 확장 할 수 없습니다. 이는 유틸리티 클래스에 대한 모범 사례입니다. private 생성자 만 선언했기 때문에 다른 클래스는이를 확장 할 수 없지만 클래스를 final로 표시하는 것이 좋습니다.


Sonar를 모르지만 개인 생성자를 찾고 있다고 생각합니다.

private FilePathHelper() {
    // No-op; won't be called
}

그렇지 않으면 Java 컴파일러는 실제로 원하지 않는 공용 매개 변수없는 생성자를 제공합니다.

(프라이빗 생성자 만 있기 때문에 다른 클래스에서는 확장 할 수 없지만 최종적으로 만들어야합니다.)


인스턴스가없는 열거 형을 사용합니다.

public enum MyUtils { 
    ; // no instances
    // class is final and the constructor is private

    public static int myUtilityMethod(int x) {
        return x * x;
    }
}

이것을 사용하여 호출 할 수 있습니다.

int y = MyUtils.myUtilityMethod(5); // returns 25.

모범 사례는 클래스가 생성 된 경우 오류를 발생시키는 것입니다.

예:

/**
 * The Class FooUtilityService.
 */
final class FooUtilityService{

/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {

    // Throw an exception if this ever *is* called
    throw new AssertionError("Instantiating utility class.");
}

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

이렇게하면 매개 변수가없는 기본 생성자가 코드의 다른 곳에서 사용되지 않습니다.


개인 생성자를 추가합니다.

private FilePathHelper(){
    super();
}

유틸리티 클래스를 최종적으로 만들고 개인 생성자를 추가하십시오.


SonarQube 문서static 는 클래스 선언에 키워드를 추가 것을 권장 합니다.

즉 변화이다 public class FilePathHelperpublic static class FilePathHelper.

또는 개인 또는 보호 생성자를 추가 할 수 있습니다.

public class FilePathHelper
{
    // private or protected constructor
    // because all public fields and methods are static
    private FilePathHelper() {
    }
}

참고URL : https://stackoverflow.com/questions/14398747/hide-utility-class-constructor-utility-classes-should-not-have-a-public-or-def

반응형