登录
首页 >  Golang >  Go问答

减少在类似结构之间手动更新字段的工作量:Golang 重构指南

来源:stackoverflow

时间:2024-03-06 12:00:26 196浏览 收藏

本篇文章给大家分享《减少在类似结构之间手动更新字段的工作量:Golang 重构指南》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在使用 graphql 和 go-pg。

我有很多这样的实体:

type player struct {
    id        int
    createdat time.time `pg:"default:now(),notnull"`
    teamid    int `pg:",notnull"`
    team      *team
    type      int
    score     int64 `pg:",notnull"`
    note      *string
    // and others...
}

type playerinput struct {
    teamid  int
    type    int
    score   int64
    note    *string
    // and others...
}

我有很多次这样的函数:

func (db *postgres) update(context context.context, id int, input types.playerinput) (*types.player, error) {

    var actualplayer types.player

    newplayer := graphqltodb(&input)

    tx, err := db.begin()
    //handle err

    err = tx.model(&actualplayer).where("id = ?", id).for("update").select()
    // handle err and rollback

    actualplayer.teamid = newplayer.teamid
    actualplayer.type = newplayer.type
    actualplayer.score = newplayer.score
    actualplayer.note = newplayer.note
    // and others...

    _, err = tx.model(&actualplayer).wherepk().update()
    // handle err and rollback

    err = tx.commit()
    //handle err

    return &actualplayer, nil
}

func graphqltodb(input *types.playerinput) *types.player {

    var output = &types.player{
        teamid:   input.teamid,
        type:     input.type,
        score:    input.score,
        note:     input.note,
        // and others...
    }

    if input.type == "example" {
        output.score = 10000000
  }

    return output
}

我的项目中的每个实体都有这个代码,我想限制/避免冗余代码,特别是:

  1. 每次都从 graphql 输入类型进行转换

    newplayer := graphqltodb(&input)
    
  2. 每次手动更新这些(和其他)字段

    actualplayer.teamid = newplayer.teamid
    actualplayer.type = newplayer.type
    actualplayer.score = newplayer.score
    actualplayer.note = newplayer.note
    
  3. 每次打开和关闭数据库事务

    tx, err := db.Begin()
    

我是在向月亮祈求吗?


解决方案


我认为这段代码中没有异常数量的冗余。

将结构从外部模型转换为内部模型是一种常见模式,有助于分离关注点。此外,您已经拥有 graphqlToDB 函数,该函数允许您重用其主体中的 10 行代码。这可能已经是最好的了。

在此处显示的特定代码段中,actualPlayer 的类型为 types.Player,并且 graphqlToDB 函数返回 *types.Player 对象。

因此,您可以简单地编写 actualPlayer := graphqlToDB(&input) ,然后传递指针,例如 tx.Model(actualPlayer) 。 这可以保存将 newPlayer 重新映射到 actualPlayer

如果每次都需要以事务方式访问数据库,那么每次都需要打开事务(然后提交/回滚)。这其中没有多余的内容。重构可能只会导致可读性的损失。

终于介绍完啦!小伙伴们,这篇关于《减少在类似结构之间手动更新字段的工作量:Golang 重构指南》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>