Even if you need to compute them once don’t do it in an initialiser like that. This is why streams can be bad, a simple line initialisation is actually a bigger computation; and just because you can write it on a line doesn’t mean you should.
You asked why a constant may require calculation. I gave an example where this can be the case. Just because a constant needs sone calculation doesn't make it any less a constant.
There are examples in compression and encryption where these constants can't even be pre-computed and loaded from say a database, but we don't even have to look further than Java's Pattern#compile method for constants that are almost always static and require some significant calculation.
I am not saying though that multiple threads should be allowed, but I can't help but wonder how much stuff would break if Pattern#compile did this.
Your mixing terminology though. A physical constant is often only calculated once, because it never changes. Sounds like your taking about invariants, which are constant over a certain portion of calculations.
Really though, you shouldn’t do such things in a static initialiser, because that’s not where large calculations should go, and they are part of a class initialisation phase lower than user level.
I wonder if the obsession with immutable classes is why many don’t see an issue with this.
8
u/r0estir0bbe Mar 21 '21
Why not? That seems like a valid use case to me, e.g. for computing specific constants - not great, but not terrible?