Reputation: 2363
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.
Upvotes: 3
Views: 324
Reputation: 2071
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.
enum
s: 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.singleton
or factory
patterns can be applied (or register the object in a DI framework).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.
Upvotes: 3
Reputation: 19120
To give an over simplified answer, I believe it's best to place them where you would expect to find them. Meaning, categorize them. This relates to the cohesion principle. Advantages of this are that you will find them easier when you need them. You can easily include only the constants you need, without polluting your namespace with other unused ones.
Another important note is, if possible, group related constants into enums. E.g. alignment constants would go into an enum Align.
Upvotes: 0