如何避免对具有不同功能的相同模式进行 go lint 重复?
我在 go 中重构代码时遇到困难,因为 lint 检测到模式的重复,但功能不同。
代码是这样的,它是通过 protobuf 定义为 grpc 实现的,
func (svc *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {
err := svc.validateCreateUser(req)
if err != nil {
return nil, err
}
user, err := svc.repo.CreateUser(ctx, req)
if err != nil {
return nil, err
}
return user, nil
}
func (svc *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {
err := svc.validateUpdateUser(req)
if err != nil {
return nil, err
}
user, err := svc.repo.UpdateUser(ctx, req)
if err != nil {
return nil, err
}
return user, nil
}
提前致谢。
我不知道如何避免重复,因为该函数也有不同的参数类型。
I have difficulties refactoring code in go, since the lint detects duplication of pattern but the function is different.
the code goes like this, it is implemented for grpc with protobuf definition
func (svc *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {
err := svc.validateCreateUser(req)
if err != nil {
return nil, err
}
user, err := svc.repo.CreateUser(ctx, req)
if err != nil {
return nil, err
}
return user, nil
}
func (svc *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserResponse, error) {
err := svc.validateUpdateUser(req)
if err != nil {
return nil, err
}
user, err := svc.repo.UpdateUser(ctx, req)
if err != nil {
return nil, err
}
return user, nil
}
thanks in advance.
I have no clue how to avoid duplication since the function also have different param type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并非所有 lint 问题都必须修复
如果您认为这会牺牲可读性,请添加 // nolint
但是...您可以使用泛型重构它们的代码
如果您认为这是可读的,请继续。
但也许这可能不是正确的方法。
例如,您的存储库可以在创建/更新之前验证请求。
恕我直言,这是比使用泛型和函数指针更具可读性的方法
Not all lint issues must be fixed
If you think it will sacrifice readability, add a // nolint
However… you can refactor them code using generics
If you think this is readable, go ahead.
But perhaps this may not the right way.
For instance, your repo can validate the request before create/update.
This is a more readable approach than use generics and function pointers IMHO