Constant is really useful?

Asked

Viewed 173 times

11

  • Why would I use a constant instead of a variable?
  • In addition to readability, there is another gain in using a constant?

I can’t make a difference that makes me use a constant instead of a variable.

1 answer

12


I do not know if there is greater readability. Until it has to be considered that it indicates better the intention of the value to be constant.

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

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

There are other contexts where the term constant does not always mean truth constant. There is transient constancy, which seems a contradiction in at least naming this constant mechanism. So at some point the variable must keep its value constant, but we’re still talking about a variable.

It has language that calls constant what is even prevented from changing the value. Run away.

Immutability is a good thing, constancy is an immutability taken to the extreme. But to abuse 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 indirect for the value that every variable has to some degree. Not all languages do this.

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


*Truth constant is a fixed value that the code has. It is a name that we use in the code but that is always replaced by a fixed value already defined in the compilation. Some people confuse it with literal. Behold What is the difference between const and readonly?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.