Is constant really useful?

  • why would I use a constant instead of a variable?
  • besides readability, is there another gain in using a constant?

I can't notice a difference that makes me use a constant instead of a variable.

Author: Maniero, 2017-05-08

1 answers

I don't know if there is higher readability. It is even considered that it better indicates the intention of the value to be constant.

The constant, as long as it is constant even*, it has the advantage of protection, any attempts to write on it will not work. If that's what you want, then it's interesting that the compiler helps in this.

Note that it is very common to call Read-Only variables constant. If the value is determined at runtime it is not a classical constant, it is a variable that cannot have its value exchanged, can only be initialized.

There are other contexts where the term constant does not always mean true constant. There is the transient constancy, which seems a countersense to at least name this constant mechanism. So at some point the variable must keep its value constant, but we are still talking about a variable.

Has language that calls a constant what is even prevented from changing the value. Flee.

Immutability is a good thing, constancy is an immutability taken to the extreme. But abusing immutability can be harmful. It has design pattern that uses immutability to simplify the use of constants.

Constant can be better optimized and use its direct value instead of having a indirection for the value that every variable has to some degree. Not all languages do this.

If the data cannot change, why not ensure this and avoid accidents? So whenever that is your situation prefer constant. It can even cause less problems one day having to make the constant into a variable, than the reverse. But even then it can have problems if there is the presumption that that value will never change. So she is very useful, just not fundamental. It's possible to rely on conventions, but I wouldn't do that.


*true Constant is a fixed value that the code has. It's a name we use in code but that is always replaced by a fixed value defined already at the compilation. Some people confuse it with literal . See What is the difference between const and readonly?.

 12
Author: Maniero, 2020-05-15 15:08:07