减少在类似结构之间手动更新字段的工作量: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 }
我的项目中的每个实体都有这个代码,我想限制/避免冗余代码,特别是:
每次都从 graphql 输入类型进行转换
newplayer := graphqltodb(&input)
每次手动更新这些(和其他)字段
actualplayer.teamid = newplayer.teamid actualplayer.type = newplayer.type actualplayer.score = newplayer.score actualplayer.note = newplayer.note
每次打开和关闭数据库事务
tx, err := db.Begin()
我是在向月亮祈求吗?
解决方案
我认为这段代码中没有异常数量的冗余。
将结构从外部模型转换为内部模型是一种常见模式,有助于分离关注点。此外,您已经拥有 graphqlToDB
函数,该函数允许您重用其主体中的 10 行代码。这可能已经是最好的了。
在此处显示的特定代码段中,actualPlayer
的类型为 types.Player
,并且 graphqlToDB
函数返回 *types.Player
对象。
因此,您可以简单地编写 actualPlayer := graphqlToDB(&input)
,然后传递指针,例如 tx.Model(actualPlayer)
。
这可以保存将 newPlayer
重新映射到 actualPlayer
如果每次都需要以事务方式访问数据库,那么每次都需要打开事务(然后提交/回滚)。这其中没有多余的内容。重构可能只会导致可读性的损失。
终于介绍完啦!小伙伴们,这篇关于《减少在类似结构之间手动更新字段的工作量:Golang 重构指南》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习