# 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");
        }
    }

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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