# Hide Default Constructor In Utility Classes

# Description

Utility classes are classes containing static properties only. Those classes should not be instantiated. A private constructor, which throws an IllegalStateException, is introduced to utility classes by this rule, if the following criteria are met:

  • Only static methods and fields are present
  • No constructor is declared
  • No main method is defined
  • The default constructor isn't invoked anywhere in the current workspace

This hides the default public constructor and thus prevents the instantiation of such a class.

# Benefits

Prevents the bad practice of unnecessary instatiation of utility classes.

# Tags

# Code Changes

Pre

    public class UtilityClass {
        public static void doSomething() {
            //...
            System.out.println("did something");
        }

        public static void doSomethingElse() {
            //...
            System.out.println("did something else");
        }
    }

Post

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

        public static void doSomething() {
            //...
            System.out.println("did something");
        }

        public static void doSomethingElse() {
            //...
            System.out.println("did something else");
        }
    }

🛠️ Auto-refactor Available

You can auto refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID HideDefaultConstructorInUtilityClasses
First seen in jSparrow version 3.11.0
Minimum Java version 1.1
Remediation cost 5 min
Links