doushouxie7064 2017-02-18 16:28
浏览 10

Golang代码结构

Is it worth to group methods in structs: For example:

type UserManager struct {
    DB *sql.DB
}

func (m UserManager) Insert (u User) error {...}
func (m UserManager) Delete (u User) error {...}
...

Or is it simpler support just separate functions.

func InsertUser (u User, db *sql.DB) error {...}

While second approach looks simpler at first, in future this way, there may be to many functions in package. Should I make separate package for every domain aggregate? In examples, I've seen so far, there is just model package. I've been working mainly with OO languages so need some advice for go best practices here.

  • 写回答

2条回答 默认 最新

  • dousi3362 2017-02-18 18:24
    关注

    Your second suggestion is not good go code! Why? Because in the best case a function should take interfaces as an input.

    So a InsertUserfunction should look something like that and it would combine your first with your second suggestion:

    type Inserter interface {
       Insert(User)error
    }
    func InsertUser(i Inserter) error {...}
    

    In that case testing of your function is easy, because you can easy mock the inserter.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大