Hide Utility Class Constructor : Utility classes should not have a public or default constructor

前端 未结 10 1240
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 03:51

I am getting this warning on Sonar.I want solution to remove this warning on sonar. My class is like this :

public class FilePathHelper {
    private static Stri         


        
相关标签:
10条回答
  • 2021-01-30 04:24

    You can just use Lombok with access level PRIVATE in @NoArgsConstructor annotation to avoid unnecessary initialization.

    @NoArgsConstructor(access = AccessLevel.PRIVATE)

    public class FilePathHelper {

    // your code

    }

    0 讨论(0)
  • 2021-01-30 04:26

    If this class is only a utility class, you should make the class final and define a private constructor:

    public final class FilePathHelper {
    
       private FilePathHelper() {
          //not called
       }
    }
    

    This prevents the default parameter-less constructor from being used elsewhere in your code. Additionally, you can make the class final, so that it can't be extended in subclasses, which is a best practice for utility classes. Since you declared only a private constructor, other classes wouldn't be able to extend it anyway, but it is still a best practice to mark the class as final.

    0 讨论(0)
  • 2021-01-30 04:27
    public class LmsEmpWfhUtils {    
        private LmsEmpWfhUtils() 
        { 
        // prevents access default paramater-less constructor
        }
    }
    

    This prevents the default parameter-less constructor from being used elsewhere in your code.

    0 讨论(0)
  • 2021-01-30 04:29

    Best practice is to throw an error if the class is constructed.

    Example:

    /**
     * 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.");
    }
    
    0 讨论(0)
提交回复
热议问题