SQL: avoiding hard-coding or magic numbers

后端 未结 11 1426
无人及你
无人及你 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:03

    We've taken a simple approach: Add a column named 'code' that contains a string that, once a record is created, is never changed.

    If you hard-code the ID value you have problems - what if you deploy some functionality (such as stored procedures that hard-code an ID and assume you'll create the corresponding record with that ID value) to another database instance that already has that ID value used by another record? Or your code is deployed as SQL scripts that create the tables and data - and you cannot guarantee each deployment will generate ID values in the same way.

    If you hard-code a field like 'Name' - there is a good chance 'Name' is displayed somewhere. What happens if the field is user-maintainable? If someone decides to change a Name value they break your procedures and functions. Even if it is not user-maintainable, some change in future will say 'We have to change the Name' and that will get done by SQL, breaking your dependent code and requiring a search for all dependencies, fixing same and testing all over again.

    But if you create a 'Code' column that never changes, who cares if the Name value changes? Name is shown to the users - they can see what they want. Code is visible only to developers, and if absolutely necessary they can later comment the code to say 'Code value X refers to Y - the name changed as part of request number Z'.

    Very simple approach.

提交回复
热议问题