dr2898 2016-03-22 23:13
浏览 68
已采纳

定义数据库ID常量/变量的最佳实践是什么

I find that when I am working on a project it often simplifies things to define variables or constants that represent database ID fields. In golang I have a constants.go file with

const (
   //SELECT ID FROM dbo.MyTable
   MYTABLEID_NO    = 1 // MyTable ID for NO
   MYTABLEID_YES   = 2 // MyTable ID for YES
   MYTABLEID_MAYBE = 3 // MyTable ID for MAYBE
)

Is this considered bad practice? how might I get around doing this if it is? Is there a more dynamic way of doing this in golang? If for some reason an ID changes, new IDs are added or the table has many IDs this way of doing things starts to break down.

  • 写回答

1条回答 默认 最新

  • douyun3887 2016-03-22 23:26
    关注

    Your are likely to get wildly different answers on this as it merely boils down to preference. I would not consider this to be an example of a bad practice. If you are not using a orm mapper then constants or enums would be a good way to represent "typeification". There are two questions you should ask yourself.

    1. Will the values change once established.
    2. Will there need to be loose coupling between the code and the database.

    If the answer to #1 is yes then I would look into pulling your values from a type table as it would be counter intuitive having constants or enumerations in the first place. (If the types are core to your application and no other client applications need to be modified when values are added then this would be easier to maintain and use in logic comparisons)

    If the answer to #2 is yes then I would look into an orm mapper or other ways to express your constant range dynamically. If you can't respond to changes to the database then that puts you in a predicament.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探