Skip to main content

Should I use accessors or public static fields for global constants? [Resolved]

I have to work on some code that was CAST-audited. The report says that it is bad in Java to use public static and that accessors should be preferred. That is also what I was taught at school.

The application uses public static fields in various classes to define the values that should be used in attributes etc.

Coming from the Typescript world, I am not sure if should change all the public constants in the application for private fields that are only accessible though getters. Thinking of it, I never saw such a practice (access constants through accessors) in Java.

Should I change all the "global constants" (there are many of them in the project) from public to private/ accessed through Getter?


Question Credit: Pikuni
Question Reference
Asked April 16, 2019
Posted Under: Programming
33 views
1 Answers

Might I suggest first and foremost, not doing bulk rewrites of the entire source tree. :)

That aside, there are pros and cons to using constants and accessors. Using constants often allows data to be available to Java at compile time instead of just run time (of course it depends on what the data type is, and how you set that data). This will likely be slightly faster, as it will inline that data, but you should always prove this out with some data-driven performance testing if you're going to make a sweeping change. That said, inlining constants also leads to static dependencies between different libraries. Consider if you inlined a value of 5 (for example), gathered from a RUN_MODE_QUICKLY constant. But in the an update of this library, they rearranged the values, and now 6 means RUN_MODE_QUICKLY, and 5 means RUN_MODE_VERY_SLOWLY. Code would "break" -- perhaps so subtly nobody would notice. There are also concerns about interned Strings using up all the object references, but I might be a little out of date here.

So you can decouple this by using accessors. Instead of inlining the values, call a function (perhaps even a static one), and ask the library to give you the data. Secondly, if you have a bunch of accessors for everthing, it's a little more future-safe in case you need to go perform some operation on every access (e.g., print some log message, or even set a breakpoint to observe all accesses).

Ultimately, it depends on your use case. Are the constants used between JAR files? If not, constants can be faster, and seem like a lot less typing, and a lot more readability. Do you need the flexibility of massaging values on every access? Perhaps accessors.


credit: cyberbisson
Answered April 16, 2019
Your Answer