Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants and Maintainability

I have a simple question that relates to good programming practices. Specifically, I am curious to the proper way to handle grouping constants. In school, they taught us to place our constants at the top of the file in which they are fist declared (usually a class file and there is some variation by professor). Now, I have seen in several places in the industry in which ALL constants are pulled out and rolled into one big include-type file.

In the first case, it made sense to pull constants out as this was code for cellphone games that had to be rapidly ported to an amazing variety of devices and this provided a centralized place to work from. But, later on, I find this practice repeated is a completely different scenario (In-house code for a public utility) with little justification as to why this is so (basically, "because that is how he have always done it").

So, what would the best practices be? I know it may seem mundane, but I have always been told that starting good habits early is the key to success.

like image 974
MysteryMoose Avatar asked Jan 30 '26 10:01

MysteryMoose


1 Answers

Treating all constants equally is usually an oversimplification. Each one has a different meaning in its context, and the way I treat them varies accordingly. Below is a small table of contexts vs how I handle constants in this context. Please correct me if you think there is a better approach.

  • Configuration parameters: => out of code wherever possible, to a configuration file or database.
  • UI strings: => in a resource file (for easy maintenance and localization).
  • Possible enums: Enums wrap multiple constants in the same context nicely (for example, days of the week, connection state...). I usually put the definition in the same package as it's used, or in a shared library if multiple assemblies/components will use it.
  • Global/static objects: I review my design to see if singleton or factory patterns can be applied (or register the object in a DI framework).
  • Test expectations: I usually leave them as they are, in the test method, for readability.
  • "Magic" numbers: I rarely have to use them; would possibly leave them in a semantically related class.

Other constants have their own contexts. I like to move constants out of code since, however paradoxical it may sound, constants tend to change.

For the same reason, putting all constants in one big file is bad. Let's say one of your assemblies depend only on constant X. This assembly has to be recompiled even when constant Y changes, and this change should not have affected it.

like image 173
henginy Avatar answered Feb 02 '26 03:02

henginy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!