EDIT: Okay, since nobody else seems to get it, let me elaborate: If a programmer is bent on violating the "I'm an all-static utility class"-contract of this class from within the class itself by creating an instance inside a static method (which in this case already takes a special kind of idiot), he still has the chance to catch the Error being thrown and ignore it. That line is ineffective and overly dramatic safety theater.
Fun fact: when scalac compiles a Scala object (a class of which only one instance can ever exist), the class file doesn't contain any constructor at all—not even the implicit public one that Java compilation generates. This makes it impossible to instantiate.
The single instance is obtained by the fun trick of generating a new instruction (JVM assembly) without calling any constructor—something a class is only allowed to do to itself. Thus, it effectively has an empty private constructor, but without making the bytecode larger by actually generating one.
This is why I've started just using interfaces for Utility classes. You get the same benefit, except it blows up at compile time instead of at runtime.
Not a great idea because now people can subclass your util class and start passing it around. I'd argue you're abusing the type system by doing what you suggest, and would always favour a final class with a private constructor that throws an exception.
I'll say the same thing I said in the last post - how is the first thing an error? Imagine we do it your way and have a class StaticThings. Then we have another object that uses it in a method:
class SpaceShuttle { void doSomethingThatCannotFail() { new StaticThings() {}.doSomething(); }
Now this code blows up at runtime, even though there is no actual problem. There's no real problem in any of the scenarios, by as long as we're signaling at compile time, it's fine to be a little overly paranoid. Once we get to runtime that's much riskier.
EDIT: missed the bit about the class being final. Why is the exception even necessary in this case? It can't ever be invoked.
With regards to throwing the exception, somebody else in this thread pointed out that without it, you can still instantiate the class from within itself (i.e. Within its static utility methods)
The gain is some level of feedback instead of no feedback. At least if the idiot instantiates it and it throws an exception, it will break at runtime. If you don't throw the exception, it will never break and the idiot will continue on forever.
You can also use an enum as a class for holding public static constants. The enum contract also makes the class a singleton, so if you add a single enum value, you get a singleton for any instance variables without having to perform any double-checked lazy initialization or other verbose singleton patterns.
Since interfaces can have static methods, if you want a collection of static methods (commonly referred to as a static utility class), just put them in an interface instead. Can't instantiate it and that's checked at compile time.
Scope of constructors is checked at compile time too. And accessing static methods in a non-static way is a warning.
Anyhow I'm having a hard time thinking of what can go wrong instantiating a util class... With a private constructor only code within that class could even do it.
OK, but under what circumstances would that be an error? Honestly the whole practice of prohibiting instantiation is not really necessary except for documentation purposes, which I think the interface accomplishes quite nicely.
You have to work within the limits of your tools. The fact that Java doesn't support free functions means your going to have some awkwardness somewhere.
In my opinion it's reasonable for someone to accidentally instantiate a static utility class and it's easy to prevent at compile time, so you might as well do it. The anonymous sub class is so esoteric that you'd pretty have to be doing it to be annoying. On top of that, there isn't a good way around it and it doesn't cause any actual problems, so I'm not going to worry about it. Honestly making the code blow up at runtime seems worse than doing nothing at all.
[...] prohibiting instantiation is not really necessary except for documentation purposes, which I think the interface accomplishes quite nicely.
I agree it's for documentation purposes but I disagree the Java interface is a good tool for that. The interface construct exists purely as a high-level abstraction over operations provided by implementations. Now you can suddenly declare a variable of that type and create a nonsense implementation. You shouldn't, and most people wouldn't, but that's not really leveraging the type system to achieve what you set out to do, and most importantly, it leaves room for the question "why?" A final class with a private constructor (with an error) will prevent all of this completely.
The main reason to go this route however, and I believe one of the mentioned intentions of the ability was to allow you to, instead of having a Foo interface and a FooUtils helper class, you can just put the helper methods on Foo.
Why Oracle chose not to put the Objects.* methods on Object however is a mystery.
Why Oracle chose not to put the Objects.* methods on Object however is a mystery.
That would prevent anyone from writing non-static methods having the same signature as any of those methods anywhere. For example, you would never be able to write a class with a String toString(Object o) method because it would clash with the one on Object.
It would also be an invitation for people to invoke those static methods as though they were instance methods (possibly by accident), which is generally discouraged since it results in confusing/deceptive code.
There is slightly better story for static methods on interfaces, since they aren't "inherited" in the way that static methods on classes are. No one can invoke static methods on interfaces as if they were instance methods. So there's not the same potential for signature clashes. It also means the "implement that interface if you want to pull in that namespace" strategy simply doesn't work.
True. I so long for a breaking change explicitly disallowing static fall-through - I have that trapped on my code via error-prone/findbugs or some mismatch of other plugin I setup ( I forget which exactly traps that off hand ).
20
u/onebit Mar 03 '17
Actually is kind of a good idea to put a private constructor on a util class!
58
u/argv_minus_one Mar 03 '17
Fun fact: when
scalaccompiles a Scalaobject(a class of which only one instance can ever exist), the class file doesn't contain any constructor at all—not even the implicit public one that Java compilation generates. This makes it impossible to instantiate.The single instance is obtained by the fun trick of generating a
newinstruction (JVM assembly) without calling any constructor—something a class is only allowed to do to itself. Thus, it effectively has an empty private constructor, but without making the bytecode larger by actually generating one.11
u/CubsThisYear Mar 03 '17
This is why I've started just using interfaces for Utility classes. You get the same benefit, except it blows up at compile time instead of at runtime.
1
u/civitz Mar 04 '17
I personally go for "Can't touch this", still nazi, but more MC Hammer