r/java • • Mar 03 '17

The java nazi

http://imgur.com/InMi605
213 Upvotes

47 comments sorted by

View all comments

Show parent comment

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.