# What is the point of calculating these variables this way?

I'm skimming through a very popular game's source code at the moment and I came across these variables inside of this class.

``````public static final BlockPos ORIGIN = new BlockPos(0, 0, 0);
private static final int NUM_X_BITS = 1 + MathHelper.calculateLogBaseTwo(MathHelper.roundUpToPowerOfTwo(30000000));
private static final int NUM_Z_BITS = NUM_X_BITS;
private static final int NUM_Y_BITS = 64 - NUM_X_BITS - NUM_Z_BITS;
private static final int Y_SHIFT = 0 + NUM_Z_BITS;
private static final int X_SHIFT = Y_SHIFT + NUM_Y_BITS;
private static final long X_MASK = (1L << NUM_X_BITS) - 1L;
private static final long Y_MASK = (1L << NUM_Y_BITS) - 1L;
private static final long Z_MASK = (1L << NUM_Z_BITS) - 1L;
``````

What is the point of initializing these this way instead of just calculating it once and initializing with the answer?

• Because these are static fields, the expressions are indeed "calculated once", since all of the expressions are calculated once and only once, when the class is loaded. They aren't like C macros, where the part to the right of the = is just substituted in the source code. Apr 30, 2016 at 4:33

The point in initializing them this way is that it makes it clear to the reader where the values come from.

I can look at the code and see that it is creating bitmasks for 64 bit values with parts X,Y,Z where the X and Z values must hold at least 30,000,000 and that is using the remaining space for the Y values.

Imagine the code looked like this:

``````private static final long X_MASK = 335544321
private static final long Y_MASK = 16383
private static final long Z_MASK = 335544321
``````

Would it be as clear what the values meant? Have you memorized what '2^25' is, and even if you have, do you know why '2^25' was chosen?

• Oh okay I didn't even think about it that way. I'd be more inclined to just add a detailed comment explaining the relationship if it were so important. But if you're concerned with space or something I could see someone just defining it this way and letting the end user figure it out. Apr 30, 2016 at 6:35
• The comments would tend to look like this code. It's always preferable to make your code explain itself. Apr 30, 2016 at 16:44
• @KarlBielefeldt Oh, no, not at all. In fact, `private static final long X_MASK = 0x14000001 // Bitmask for the X part` is a whole lot better than either of those forms. Apr 30, 2016 at 23:44
• Not really. What's the max value the author expected X to be?
– user53141
May 1, 2016 at 1:21