Question: What are some other strategies on avoiding magic numbers or hard-coded values in your SQL scripts or stored procedures?
Consider a stored procedure whose job is to check/update a value of a record based on its StatusID or some other FK lookup table or range of values.
Consider a Status table where the ID is most important, as it’s a FK to another table:

The SQL scripts that are to be avoided are something like:
DECLARE @ACKNOWLEDGED tinyint
SELECT @ACKNOWLEDGED = 3 --hardcoded BAD
UPDATE SomeTable
SET CurrentStatusID = @ACKNOWLEDGED
WHERE ID = @SomeID
The problem here is that this is not portable and is explicitly dependent on the hard-coded value. Subtle defects exist when deploying this to another environment with identity inserts off.
Also trying to avoid a SELECT based on the text description/name of the status:
UPDATE SomeTable
SET CurrentStatusID = (SELECT ID FROM [Status] WHERE [Name] = 'Acknowledged')
WHERE ID = @SomeID
Question: What are some other strategies on avoiding magic numbers or hard-coded values in your SQL scripts or stored procedures?
Some other thoughts on how to achieve this:
- add a new
bitcolumn (named like ‘IsAcknowledged’) and sets of rules where there can be only one row with a value of1. This would help in finding the unique row:SELECT ID FROM [Status] WHERE [IsAcknowledged] = 1)
At some level, there’s going to be some “hard coding” of values. The idea of eliminating them comes from two sides:
'Acknowledged'rather than3is probably going to make your intentions more obvious to the reader.Making
bitcolumns for various states can be a good or bad idea; it really just depends on the data. If the data goes through various “stages” (Received, Acknowledged, Under Review, Rejected, Accepted, Responded, etc.) then that approach quickly scales itself out of viability (not to mention the irritating process of having to ensure that only one of the columns is set to 1 at any given time). If, on the other hand, the state is really as simple as you describe, then doing that can make the code more readable and indexes perform better.The biggest no-no in hard coding values is hard coding values that reference other entities (in other words, hard coding the primary key for a corresponding object). The string
'Acknowledged‘ is still a hard-coded value, it’s just more transparent in its meaning and it isn’t a reference to something else. For me, it boils down to this: if you can (reasonably) look it up, do it. If you can’t (or if something makes it an unreasonable task either from a performance or maintainability perspective), hard code it. Using this, you can look up the value of 3 by usingAcknowledged; you can’t look upAcknowledgedfrom anything else.