golang反模式中的基本API? [英] Basic API in golang antipattern?

查看:17
本文介绍了golang反模式中的基本API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我,但就我对 API 的理解而言,它是允许我通过接口修改和请求数据的东西,这正是我想在 Go 中做的事情.例如我有一个用户界面:

Correct me if I'm wrong, but for my understanding of an API is that it is something that allows me to modify and request data through an interface, which is what I want to do in Go. For example I have a user interface:

interface IUser {
  GetId() int
  GetName() string
  GetSignupDate() time
  GetPermissions() []IPermission
  Delete()
}

这在我看来已经像是活动记录,如果我想用新 ID 创建一个新用户,我将不得不使用 new 因为据我所知 Go 不支持静态函数.这意味着我的界面中还需要一个提交功能,这对我来说更糟.我在这里做错了什么?

This already looks to me like active record and if I want to create a new user with a new id I would have to use new since Go doesn't support static functions as far as I know. This means I would also need a commit function in my interface, which makes it even worse for me. What am I doing wrong here?

推荐答案

在 Go 中,接口是行为性的.也就是说,他们描述的东西做什么多于它是什么.您的示例看起来像是您尝试在 Go 中编写 C#,并且在接口类前面大量使用了 I.但是,只用一种类型实现的接口有点浪费时间.

In Go, interfaces are behavioural. That is, they describe what a thing does more than what it is. Your example looks like you're trying to write C# in Go, with your heavy use of I in front of interface classes. However, an interface that is only implemented by one type is a bit of a waste of time.

相反,请考虑:

interface Deleteable {  // You'd probably be tempted to call this IDeleteable
                        // Effective go suggests Deleter, but the grammar 
                        // sounds weird
    Delete() err
}

现在您可以创建一个函数来执行批量删除:

Now you can create a function to perform batch deletes:

func BatchDelete(victims []Deleteable) {
    // Do some cool things for batching, connect to db, start a transaction
    for _, victim := range(victims) {
        victim.Delete()  // Or arrange for this function to be called somehow.
    }
}

通过为更新、序列化等创建一个接口,并在实现这些方法的具体结构中存储您的实际用户/权限/等,您可能会更快地开始.(注意在 Go 中你不必说一个类型实现了一个接口,它会自动"发生).您也不必为每个方法(更新程序、可序列化)提供一个接口,但您可以将它们全部捆绑到一个接口中:

You'd probably get started faster by creating an interface for Update, Serialize and so on, and storing your actual users/permissions/etc in concrete structs that implement those methods. (Note in Go you don't have to say that a type implements an interface, it happens "automatically"). You also don't have to have a single interface for each method (Updater, Serializable), but you can bundle them all into one interface:

type DBObject interface {
    Update()
    Serialize() RowType
    Delete()
}

type User struct {
    Id int
    Name string
    // ... etc
}

请记住,您的模型始终可以填充"一个 User 对象以从您的 API 返回,即使 User 对象的实际表示更加分散,例如RDF 三元组.

Remember, your model can always "Fill in" a User object to return from your API, even if the actual representation of the User object is something much more diffuse, e.g. RDF triples.

这篇关于golang反模式中的基本API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆