Should Helper/Utility Classes be abstract?

I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these?

What would the Pros and Cons be to declaring such a class as abstract.

public [abstract] class Utilities{

   public static String getSomeData(){
       return "someData";
   }

   public static void doSomethingToObject(Object arg0){
   }
}

Solution 1:

You could just declare a private constructor that does nothing.

The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.

Solution 2:

Don't bother making them abstract, but include a private parameterless constructor to prevent them from ever being instantiated.

Point of comparison for those interested: in C# you would declare the class to be static, making it abstract and sealed (Java's final) in the compiled form, and without any instance constructor at all. That also makes it a compile-time error to declare a parameter, variable, array etc of that type. Handy.

Solution 3:

I don't declare utility classes abstract, I declare them final and make the constructor private. That way they can't be subclassed and they can't be instantiated.



public final class Utility
{
    private Utility(){}

    public static void doSomethingUseful()
    {
        ...
    }
}

Solution 4:

I would add more step beyond the private constructor:

public class Foo {
   // non-instantiable class
   private Foo() { throw new AssertionError(); }
}

Throwing the AssertionError prevents methods in the same class from instantiating the class (well, they can try). This isn't normally a problem but in a team environment you never know what someone will do.

As regards the "abstract" keyword, I have noticed utilities classes subclassed in numerous instances:

public class CoreUtils { ... }
public class WebUtils extends CoreUtils { ... }

public class Foo { ... WebUtils.someMethodInCoreUtils() ... }

I believe this is done so that people don't have to remember which utility class to include. Are there any downsides to this? Is this an anti-pattern?

Regards, LES