DEV Community

Pascal Dennerly
Pascal Dennerly

Posted on

THIS_IS_A_CONSTANT

A junior engineer asked a great question while we were pairing

"Why does this variable have to be in upper case?"

Well, because it's static final, of course.

But why?

So I had to think about this one and wondered why myself. What's so different? And why did people decide this was a good idea?

So the obvious difference is that because it's final, it can't be modified after it has been initialised. And it's static, meaning that it's a property of the class and not of this instance.

It's as close as you really get, in Java, to a const in other languages.

But, he asked, why does that mean we have to make it upper case with underscores? Won't the compiler tell us when you try to change it?

Well it's a convention that we used to tell us that we need to use this field differently, like we used to back in the old C days, and it's stuck from there.

But what was so different about C?

So there wasn't really the concept of a immutables for a while in C either. BUT we did have the #define directive. This told the compiler that the next thing it saw on the line would be a symbol that would be replaced exactly with the thing after that.

So you would see something like:
#define STR "my string"

When the compiler saw STR, it would literally replace that symbol with "my string" when it was processing that file.

It was important to know that you were dealing with something special, something that could break in REALLY weird ways! Anyone remember the old "end of file when ';' expected - but it's RIGHT THERE!"?

So here we are in 2020, writing Java variables with different case because it looks like a constant, because we have to know to treat it differently, almost with reverence, because of lessons learned in another language.

Top comments (0)