SQL: avoiding hard-coding or magic numbers

后端 未结 11 1433
无人及你
无人及你 2020-12-14 17:18

Question: What are some other strategies on avoiding magic numbers or hard-coded values in your SQL scripts or stored procedures?

Consider a stored

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 18:00

    At some level, there's going to be some "hard coding" of values. The idea of eliminating them comes from two sides:

    1. Making the code more readable (i.e., saying 'Acknowledged' rather than 3 is probably going to make your intentions more obvious to the reader.
    2. Making the code more dynamic, where one function can take a parameter rather than several functions that don't (this is a simplification obviously, but the meaning should be fairly self-evident anyway)

    Making bit columns 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 using Acknowledged; you can't look up Acknowledged from anything else.

提交回复
热议问题