Hot Take: Not everything needs to be a constant
Hot-Takes are quick brain-dumps on practices that catch my eye and my ire.
You don’t need to turn every arbitrary string and number in your code into a constant.
Using constants in your code can contribute to code clarity, DRYness, and even performance (although speed benefits would typically be miniscule in a standard application). But the drive to turn every string and number that’s scattered throughout the code into a constant and organize/taxonomize them can easily go overboard. Take a look at the following block of code:
|
|
And following that back to the directory structure, you find something like this:
This is an example of organization gone wild. In this case, the value of
timeout
is set using a constant from app/constants/general/time.py
that
defines the number of seconds in a minute. Barring an extreme case of needing
the seconds in one minute to be configurable, you should forego a constant and
leave the literal value inside of the code where it’s used. When contributing to
or maintaining this code, there’s no real benefit to having the value be hidden
away in another file, and if the timeout does need to change, you’d presumably
need to declare a new constant, like MINUTE_AND_A_HALF = 90
to match the
current style. You could make the case that the name of the constant should
change, along the lines of TWILIO_ENDPOINT = 60
, but I’d still argue that this
is an over organization that turns 1 line of code into 2 lines split across 2
files.
Findability is hugely important in distributed systems. We can perform global searches in files, projects, and entire organizations. If a value is specifically relevant to a line of code, leave it near (or in) that line of code. Writing the code like this is so much easier to understand and modify:
|
|
And if you have an app with many constants, put them all together. It’s much easier to deal with a single file with a hundred values than twenty files with five values each.