Is it a good practice to declare all the variables in my program as a const
variable?
eg:-
private int myAge = 20;
private const int Age = 20;
Now, from the above example, which one is a good practice for declaring variables. Is declaring const
proved to be more effective in coding than just declaring a variable?
4
If the variable is actually a constant then, yes, it’s a good idea to declare it as such. If the variable is not a constant then, no, it would be a terrible idea to declare it as a constant.
Your age is unlikely to be a constant. Presumably, you age over time so you would want to perform the calculation. Something like the variable pi or the speed of light is actually a constant and should be declared as such.
If you declare non-constant values as constants then you’d have to re-deploy code every time those values change. If you have only one variable in your code base and you know when your age changes, that would be a bunch of extra work to track and fix every year but it could be done. Real applications, though, have lots of different variables that change at different rates. Keeping track of all of them would mean that you’d be constantly deploying code just to change “constant” values. Many of those deploys will come at inopportune moments– month ends, holidays, during vacations, during periods of peak load, etc. And inevitably, you’ll miss some.
3