Are constants as evil as global variables and singletons?

前端 未结 3 434
迷失自我
迷失自我 2020-12-29 00:07

I\'ve heard many times on this forum that using global variable is a dead sin and implementing singleton is a crime.

It just came to my mind that old good constants

3条回答
  •  伪装坚强ぢ
    2020-12-29 00:52

    The primary reason why global variables are considered bad practice is because they can be modified in one part of a system and used in another part, with no direct link between those two pieces of code.

    This leads to potential bugs because it is possible to write code that uses a global variable without knowing (or considering) all the places where it is used and ways in which it could be changed. Or vice-versa, write code that makes a change to a global, without realising the impact that change may have in other unrelated parts of your code.

    Constants do not share this issue, because they are... well, constant. Once they're defined, they can't be changed, and thus the issued described in the above paragraph cannot occur.

    Therefore, they are fine to use globally.

    That said, I have seen some poorly written PHP code that uses define to create constants, but declares the constants differently in different circumstances. This is a mis-use of constants: A constant should be an absolutely fixed value; it should only ever be a single value. If you have something that could potentially be different values on different runs through the program, then it shouldn't be defined as a constant. That sort of thing should indeed be a variable, and then should follow the same rules as other variables.

    This sort of mis-use can only happen in a scripted language like PHP; it couldn't happen in a compiled language because you can only define a constant once, in one place and to a fixed value.

提交回复
热议问题