r/java • • Mar 03 '17

The java nazi

http://imgur.com/InMi605
213 Upvotes

47 comments sorted by

20

u/onebit Mar 03 '17

Actually is kind of a good idea to put a private constructor on a util class!

25

u/kodifies Mar 03 '17

Actually its a good idea to put a private constructor on a util class!

FTFY

no kind of about it!!!

8

u/[deleted] Mar 03 '17

Actually its a good idea to put a private constructor on a util class!

FTFY

Actually it's a good idea to put a private constructor on a util class!

FTFY

And we're back to the grammar Nazi.

7

u/you-suck-at-grammar Mar 03 '17

Actually it's a good idea to put a private constructor on a util class!

FTFY

And we're back to the grammar Nazi.

It's actually a good idea to put a private constructor on a utility class.

FTFY

1

u/[deleted] Mar 03 '17

That's no grammar

-Semantics Nazi

0

u/kodifies Mar 03 '17

nooo, nothing to do with grammar

-3

u/stitzl Mar 03 '17

Throwing an Error from said constructor is what makes it a bit absurd, though.

7

u/ForeverAlot Mar 03 '17

A private constructor can still be invoked from within the class. The error prevents that.

0

u/stitzl Mar 03 '17 edited Mar 04 '17

That is exactly what I was referring to.

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.

2

u/thatsIch Mar 04 '17

reflection is just one way

58

u/argv_minus_one Mar 03 '17

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.

24

u/xjvz Mar 04 '17

This makes it impossible to instantiate.

That's where you're wrong, kiddo.

16

u/argv_minus_one Mar 04 '17

I was hoping I didn't have to qualify that statement with “unless you're a filthy sadist who enjoys torturing innocent JVMs.” :P

4

u/jnordwick Mar 04 '17

Thought your username said orgy_minus_one

4

u/Wolfsdale Mar 04 '17

You can do that too with sun.misc.Unsafe. I wouldn't be surprised if it uses that on Oracles JVM. http://www.docjar.com/docs/api/sun/misc/Unsafe.html#allocateInstance(Class)

2

u/SmoothB1983 Mar 04 '17

That is hilarious and actually I can see a few uses for it.

2

u/xjvz Mar 04 '17

Mockito, EasyMock, etc, all use this. I think it started as a library from EasyMock in the first place actually.

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.

21

u/Artraxes Mar 04 '17

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.

-1

u/CubsThisYear Mar 04 '17

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.

2

u/mhixson Mar 04 '17

Why is the exception even necessary in this case? It can't ever be invoked.

It's not necessary. It's a matter of style, kind of like a comment.

2

u/yawkat Mar 04 '17

Serialization frameworks will use the no-arg constructor

1

u/stitzl Mar 04 '17

But only if they are handed an instance, which they never are.

2

u/yawkat Mar 04 '17

No, I'm talking about the deserialization part. Like gson does.

1

u/Artraxes Mar 04 '17

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)

1

u/stitzl Mar 04 '17

Same idiot can then go on to catch the Error, so what is gained?

3

u/Artraxes Mar 04 '17

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.

6

u/xjvz Mar 04 '17

Easier way to do this would be an enum with no values:

public enum SomeUtil {
    ;
    public static void foo() {
        // ...
    }
}

1

u/m-r-r Mar 05 '17

That's clever ! I'm going to use that in my next project, thanks for suggesting :-)

3

u/xjvz Mar 05 '17

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.

3

u/pushthestack Mar 03 '17

How do you mean?

11

u/CubsThisYear Mar 03 '17

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.

3

u/beeeeeeefcake Mar 04 '17

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.

2

u/meotau Mar 03 '17

I could still make an anonymous class.

2

u/CubsThisYear Mar 03 '17

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.

1

u/meotau Mar 03 '17

That's true, but nobody wants to see the instantiation of an util class/interface. So why not to prohibit something which should never be done?

3

u/CubsThisYear Mar 03 '17

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.

1

u/ForeverAlot Mar 04 '17

[...] 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.

-2

u/experts_never_lie Mar 03 '17

You can even have a class implement that interface if you want to pull in that namespace …

17

u/LittleLui Mar 03 '17

That makes Baby Jesus cry. Please use a static import instead.

3

u/the_anj Mar 03 '17

That's a good example of a just because you can, doesn't mean you should

1

u/talios Mar 04 '17

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.

4

u/mhixson Mar 04 '17

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.

1

u/talios Mar 04 '17

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 ).

3

u/zjs Mar 04 '17

You get the same benefit, except it blows up at compile time instead of at runtime.

Invoking a private constructor will blow up at compile time.

The only situation where the AssertionError would get thrown is if you accidentally added code to the class itself that invoked the constructor.

3

u/__konrad Mar 04 '17

The only situation where the AssertionError would get thrown is if you accidentally added code to the class itself that invoked the constructor.

java.lang.reflect.Constructor c = java.util.Objects.class.getDeclaredConstructor();
c.setAccessible(true);
c.newInstance(); // no soup for you!

1

u/civitz Mar 04 '17

I personally go for "Can't touch this", still nazi, but more MC Hammer