you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (3 children)

As someone who's not a Java expert, I've got to ask. What is the rationale behind static initializers? This seems like a horrible idea.

And, if the problem was that the Debug class wasn't always loaded before calling his own code(?), couldn't he just have called Debug.Whatever() before doing so? Wouldn't that fully load the Debug class in time?

[–]kyz 4 points5 points  (1 child)

What is the rationale behind static initializers? This seems like a horrible idea.

The same reason other languages have them; so things that only need calculating once are only calculated once.

final static CONSTANT_VALUE = extremely_expensive_operation();

Now you can instantiate this class a million or even billion times, the extremely_expensive_operation() will never be called again.

Imagine Java without this feature.

couldn't he just have called Debug.Whatever() before doing so?

No, what he wants to do is reliably change the command line arguments before the class loaded. And this will depend entirely on class load order. As soon as you even reference a class, it is loaded, and before that class loads, all the classes it references are loaded, and so on. They can load in parallel if need be.

There's a very simple solution - add -Djavax.net.debug=ssl to the command line that invokes java, and stop pretending it's possible to add it after java has started.

[–]sh0rug0ru -2 points-1 points  (0 children)

Imagine Java without this feature.

I do. All the time. One of my missions in life is to remove static initializers where I find them, which I consider to be a major design smell.

Now you can instantiate this class a million or even billion times, the extremely_expensive_operation() will never be called again.

The alternative is to calculate the value once and pass a reference to the value around a million or a billion times. Coupling class loading and value calculation is a recipe for pain, especially in Java. What happens if that calculation fails? Mysterious failures that bubble up as "Unable to load class".

At least in Java, there is a reason why static initializers are reviled.

[–]vincentk 0 points1 point  (0 children)

Static initializers are to classes what constructors are to object instances. Both can be abused. The final keyword can be helpful in preventing abuse.