How to organise your application’s constants
Organising global variables and application-level constants is hard. The interwebs is littered with questions on this topic and the answers are all over the place as expected. After all, the world would stop spinning if programmers agreed on the one right way to do anything.
After many trials and tribulations over different projects, I have settled on a convention that has served me well. I simply apply these principles:
- I should be able to look up a constant value and validate it
- References to constants in the code should be readable
- Related constants should be grouped together and be retrievable as enums.
- Classes with constants should only have constants
All my constants classes extend an abstract
Constants class as shown below (available as a package at https://github.com/koomai/constants):
For example, if I need to have
status values for leads/customers in a CRM application, I create a
LeadStatus class which extends the
Constants class above:
Now I can use readable constants in my code and avoid having string values all over the place.
Here are some snippets as examples: