55

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){
   }
}

11 Answers 11

88

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.

3
  • 10
    And probably declare it final to make your intent absolutely clear.
    – tvanfosson
    Nov 21, 2008 at 17:52
  • 11
    Sadly, you can't declare it abstract final. :-) Nov 21, 2008 at 18:35
  • 4
    He wasn't suggesting he should... :| Jan 30, 2009 at 2:38
20

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.

13

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()
    {
        ...
    }
}
1
  • Using this format that you suggest above, should I use a "static import" line to import the class methods for use in my project?
    – djangofan
    Aug 23, 2012 at 0:36
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

3

By declaring them as abstract, you are in effect indicating to other coders that you intended for these classes to be derived from. Really, you're right, that there's not much difference, but the semantics here are really more about the interpretation of other people who look at your code.

2

As others stated, make a private parameter-less constructor. No-one can create an instance of it, apart from the class itself.

As others have shown how it is done with other languages, here comes how you do it in the next C++ version, how to make a class non-instantiable:

struct Utility { 
    static void doSomething() { /* ... */ } 
    Utility() = delete; 
};
2

I think it's better to declare utility classes final with a private no-args constructor. Moreover all members of this class should be static.

An easy way to do all this in one statement is to use the @UtilityClass annotation of Lombok:

@UtilityClass
public class Utilities{

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

   public void doSomethingToObject(Object arg0) {
   }
}

If you use the @UtilityClass annotation you can skip the static keywords as in the example above since Lombok adds them automatically during compilation.

0

No, but if your language supports it, there's a strong argument to be made that in most cases they should (can) be declared as 'static'... Static tells the compiler that they cannot be instantiated, and that all methods in them must be static.

Abstract is for classes that DO have instance-based implementation details, which WILL be used by instances of derived classes...

3
  • 1
    java classes can't be declared as static, can they? Perhaps I'm just misunderstanding your point?
    – shsteimer
    Nov 21, 2008 at 17:36
  • Sorry, I'm .Net guy... & didn't notice the java tag... Then if java classes cannot be declared static, you should make private parameterless ctor and make all members static... Nov 21, 2008 at 17:40
  • 2
    In some circumstances, a Java class can be declared as static, but it means something different.
    – erickson
    Nov 21, 2008 at 17:45
0

someone mentioned that in C# 3.0 you could accomplish this via extension methods. I'm not a C# guy, did some back in the 1.5/2.0 days, but have not used it since then. Based on a very cursory understanding I think something similar can be accomplished in java with static imports. I realize its not at all the same thing, but if the goal is to just make these utility methods seem a bit more "native"(for lack of a better term) to the calling class, I think it will do the trick. Assuming the Utilities class I declared in my original question.

import static Utilities.getSomeData;

public class Consumer {

    public void doSomething(){

        String data =  getSomeData();
    }

}
0
0

Might I offer some constructive advice?

If you are doing a lot of this, there are two problems you will run into.

First of all, a static method that takes a parameter should often be a part of the object that is that parameter. I realize this doesn't help for objects like String, but if it takes objects you've defined, you could almost certainly improve the object by including your helper as a method of that object.

If it takes all native values, you probably could define an object that it's a method of. See if you can find any grouping of those native values and group them as an object. If you just try that, you'll find a lot of other uses for that little mini-object, and before you know it it will be amazingly useful.

Another thing, if you have a utility class with a bunch of semi-related static methods and static variables, you almost always want it to be a singleton. I found this out by trial and error, but when you find out you need more than 1 (eventually you will), it's MUCH easier to make a singleton into a multipleton(?) then to try to change a static class into a multipleton(okay, so I'm making words up now).

Good luck. This stuff was mostly trial and error for me--figured it out like 5 years ago though, and I've never found an instance where I regretted not having static class/methods.

0

Helper / Utility methods are just fine. Don't worry about adding them to a library inside your application or Framework. Most frameworks that I have seen use them in many varieties.

That being said, if you want to get really crafty about them you should look into extension methods in C# 3.0. Using extension method will make your Utilities a little more of a "holistic" part of your framework which it seems like what you're trying to do by considering to make them abstract. Not to mention extension method are a lot of fun to write!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.