Java: Static Class?
Solution 1
Private constructor and static methods on a class marked as final.
Solution 2
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.
Solution 3
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
Solution 4
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
Solution 5
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.
Nick Heiner
JS enthusiast by day, horse mask enthusiast by night. Talks I've Done
Updated on July 08, 2022Comments
-
Nick Heiner almost 2 years
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?
-
Asaph over 14 yearsAlso, don't forget to make a private constructor.
-
Bill the Lizard over 14 years@Asaph: Agreed. I added a bit on that to my answer. Thanks.
-
Dan Dyer over 14 yearsSingletons are considered evil too.
-
Bennett Dill over 14 yearsYou are correct, I wonder which is considered worse. Ultimately I like to practice the solution that makes the most sense, it's entirely possible a static class is the way to go. The thing is if all methods are static, why have a private ctor? To me the private ctor is used with singleton patterns. If 'they' want an instance of a class with no members, let them have it ;-)
-
rob over 14 yearsYou use the private constructor to prevent anyone from instantiating or subclassing the class. See David Robles' answer: stackoverflow.com/questions/1844355/java-static-class/…
-
irreputable over 14 yearssingleton is not more evil than dependency injection:)
-
rob over 14 yearsOO 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. ;)
-
TofuBeer over 14 yearsA someone who has seen (in production code, not jsut student code) object.staticMethod I think you overestimate the abilities of Joe Random Programmer! :-P
-
Bennett Dill over 14 years@rob re private constructor. Just to make sure methodologies aren't blending, if the class at hand is comprised of static members, it has no members participating in OO and subclassing it get's you nothing. So why have a private ctor on a class with static methods. To me if you want to prevent subclassing, final is the way to go. Now, if you're creating a class that you want to use in a singleton pattern, then a private ctor makes sense. Because you can place the static instance on the class and it can be responsible for the single instance.
-
Bennett Dill over 14 years@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
-
kyoryu over 14 years@rob: Can't argue too much with that for pure functions. For everything else, static/singleton/global are pretty much all evil :)
-
Tom over 14 years@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 :-).
-
Rui Marques about 11 yearsIf you want static methods within an inner class, the class has to also be static.
-
Pacerier almost 10 yearsSo is java.lang.Math "death to testability"?
-
Pacerier almost 10 yearsWhy did you choose
AssertionError
over other alternatives likeIllegalStateException
,UnsupportedOperationException
, etc? -
crowne almost 10 yearsIt might be interesting to see how it scores when run through code.google.com/p/testability-explorer
-
bcsb1001 over 9 years@Pacerier See this.
-
Pacerier over 9 years@bcsb1001, That brings us to this.
-
Maximilian Schulz over 5 yearsI personally consider it as a fallacy of the Java language not to have functions living outside classes (as e.g. in C++), so imho the workaround proposed (non-instantiable class with static functions) is very valid.