139

I have a class full of utility functions. Instantiating an instance of it makes no semantic sense, but I still want to call its methods. What is the best way to deal with this? Static class? Abstract?

1
  • 16
    You can't make a top level class static by the way... Commented Dec 4, 2009 at 1:51

8 Answers 8

173

Private constructor and static methods on a class marked as final.

Sign up to request clarification or add additional context in comments.

1 Comment

@matt b: As David Robles points out in his answer, you do not need to make the class final... it cannot be subclassed because a subclass will be unable to invoke a super class constructor because it is private. However... no harm in being explicit. But jfyi :-).
96

According to the great book "Effective Java":

Item 4: Enforce noninstantiability with a private constructor

- Attempting to enforce noninstantiability by making a class abstract does not work.

- A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor:

// Noninstantiable utility class
public class UtilityClass
{
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
        throw new AssertionError();
    }
}

Because the explicit constructor is private, it is inaccessible outside of the class. The AssertionError isn’t strictly required, but it provides insurance in case the constructor is accidentally invoked from within the class. It guarantees that the class will never be instantiated under any circumstances. This idiom is mildly counterintuitive, as the constructor is provided expressly so that it cannot be invoked. It is therefore wise to include a comment, as shown above.

As a side effect, this idiom also prevents the class from being subclassed. All constructors must invoke a superclass constructor, explicitly or implicitly, and a subclass would have no accessible superclass constructor to invoke.

3 Comments

Why did you choose AssertionError over other alternatives like IllegalStateException, UnsupportedOperationException, etc?
@Pacerier See this.
@bcsb1001, That brings us to this.
21

Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.

But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability

2 Comments

So is java.lang.Math "death to testability"?
It might be interesting to see how it scores when run through code.google.com/p/testability-explorer
6

Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

My $.02

8 Comments

Singletons are considered evil too.
You use the private constructor to prevent anyone from instantiating or subclassing the class. See David Robles' answer: stackoverflow.com/questions/1844355/java-static-class/…
singleton is not more evil than dependency injection:)
OO has its place, but there are times when it just isn't practical, or it would be a waste of resources--for instance, something as simple as Math.abs(). There's no reason to instantiate an object just for the sake of instantiating an object, when a static method call would have served you just as well without any of the O-O-overhead. ;)
@rob re OO, I agree, Math.Abs probably never needs an instance. When I hear "i have a utility class", I see Math.Avg(), where you now need to add supported for a weighted average. I see a Url generator, param in, url out that needs to be refactored to support href, or url only, etc etc. For these reasons, having the OO based utility class can pay back. Also, now I'll drop the standard OO defensive tactic, testing! /me ducks
|
3

comment on the "private constructor" arguments: come on, developers are not that stupid; but they ARE lazy. creating an object then call static methods? not gonna happen.

don't spend too much time to make sure your class cannot be misused. have some faith for your colleagues. and there is always a way to misuse your class no matter how you protect it. the only thing that cannot be misused is a thing that is completely useless.

1 Comment

A someone who has seen (in production code, not jsut student code) object.staticMethod I think you overestimate the abilities of Joe Random Programmer! :-P
2
  • Final class and private constructor (good but not essential)
  • Public static methods

Comments

1

There's no point in declaring the class as static. Just declare its methods static and call them from the class name as normal, like Java's Math class.

Also, even though it isn't strictly necessary to make the constructor private, it is a good idea to do so. Marking the constructor private prevents other people from creating instances of your class, then calling static methods from those instances. (These calls work exactly the same in Java, they're just misleading and hurt the readability of your code.)

3 Comments

Also, don't forget to make a private constructor.
@Asaph: Agreed. I added a bit on that to my answer. Thanks.
If you want static methods within an inner class, the class has to also be static.
-1

You can use @UtilityClass annotation from lombok https://projectlombok.org/features/experimental/UtilityClass

1 Comment

Following the link, it's experimental and use is not encouraged ('due to fundamental issues with non-star static imports')

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.