Is global constants an anti-pattern?

后端 未结 7 1650
再見小時候
再見小時候 2020-12-03 03:29

I\'ve always thought having a class just for the sake of holding constants is a bad design. But recently, I\'ve tried googling for it and found only that having an inter

7条回答
  •  生来不讨喜
    2020-12-03 04:28

    In some cases, global constants are the perfect way to go when they are truly constant (not only constant for one build of the program, but supposedly during the whole lifespan of the software product and beyond).

    For example, you wouldn't want to have several classes each declaring their own constant for pi, e or HTTP_SUCCESS.

    On the other hand, global constants can create many of the problems of global variables if they are arbitrary values that could be changed e.g. because of changing requirements. I.e. if putting those constants into a config file seems like a reasonable option, it should not be a global constant.

提交回复
热议问题