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

huangapple go评论83阅读模式
英文:

What is best practice for defining database ID constants/vars

问题

我发现在项目中工作时,定义代表数据库ID字段的变量或常量通常可以简化事情。在golang中,我有一个constants.go文件,其中包含以下内容:

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
)

这种做法被认为是不好的吗?如果是的话,我该如何解决这个问题?在golang中是否有更动态的方法?如果由于某种原因ID发生变化,新的ID被添加或表中有许多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

得分: 1

你很可能会得到完全不同的答案,因为这只是个人偏好的问题。我不认为这是一个不好的做法的例子。如果你没有使用ORM映射器,那么常量或枚举将是表示"类型化"的好方法。有两个问题你应该问自己。

  1. 这些值在确定后会改变吗?
  2. 代码和数据库之间是否需要松耦合?

如果问题1的答案是肯定的,那么我建议你从类型表中获取值,因为一开始就使用常量或枚举是不直观的。(如果这些类型对你的应用程序很核心,并且在添加值时不需要修改其他客户端应用程序,那么这种方式更容易维护和在逻辑比较中使用)

如果问题2的答案是肯定的,那么我建议你使用ORM映射器或其他方式来动态表示常量范围。如果你无法对数据库的变化做出响应,那么你就陷入了困境。

英文:

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.

huangapple
  • 本文由 发表于 2016年3月23日 07:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/36166967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定