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

前端 未结 10 1239
伪装坚强ぢ
伪装坚强ぢ 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:06

    Add private constructor:

    private FilePathHelper(){
        super();
    }
    
    0 讨论(0)
  • 2021-01-30 04:08

    I don't know Sonar, but I suspect it's looking for a private constructor:

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

    Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.

    (You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)

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

    I use an enum with no instances

    public enum MyUtils { 
        ; // no instances
        // class is final and the constructor is private
    
        public static int myUtilityMethod(int x) {
            return x * x;
        }
    }
    

    you can call this using

    int y = MyUtils.myUtilityMethod(5); // returns 25.
    
    0 讨论(0)
  • 2021-01-30 04:11

    I recommend just disabling this rule in Sonar, there is no real benefit of introducing a private constructor, just redundant characters in your codebase other people need to read and computer needs to store and process.

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

    SonarQube documentation recommends adding static keyword to the class declaration.

    That is, change public class FilePathHelper to public static class FilePathHelper.

    Alternatively you can add a private or protected constructor.

    public class FilePathHelper
    {
        // private or protected constructor
        // because all public fields and methods are static
        private FilePathHelper() {
        }
    }
    
    0 讨论(0)
  • 2021-01-30 04:23

    make the utility class final and add a private constructor

    0 讨论(0)
提交回复
热议问题