避免在Go包和结构名称中出现口吃的方法有哪些?

huangapple go评论156阅读模式
英文:

Ways to avoid stuttering in go package and struct names?

问题

我最近一直在进行一些Go编程,尝试遵循《Effective Go》的风格指南,但有时在命名包、接口和结构体时很难避免重复。举个例子,我可能有一个名为console的包,其中包含一个名为Console.go的文件,其中定义了一个Console接口、一个console结构体和一个New函数。

现在当我在其他地方使用它时,我到处都要使用console.Console类型。当一个包中有两个或更多的结构体时,我会遇到类似这样的情况:con := console.NewConsole()

我不介意有大而扁平的包结构,但我希望尽可能地保持代码的组织性。我对IO.Reader和IO.Writer的概念很满意,但是当包与实体相同时,仍然需要进行分离,应该怎么办呢?(是的,我知道给出的例子可以是Console.Writer,但假设它是完全不同的东西)

所以我的问题是:
这种重复效应是我应该担心的吗?(也就是说,这是不好的形式吗?)
有人有什么避免这种情况的建议吗?

英文:

I have been doing a bit of go programming of late and while trying to follow Effective Go style guidelines, I sometimes find it difficult to avoid stuttering when naming packages and interfaces and structs.

As an example.
I might have a console package with a Console.go file containing a Console interface a console struct and a New function.

//console/Console.go
package console

type Console interface {
   Print(s String)
}

type console struct {
  ....
}

func (c *console) Print(s String){
  ....
}

func New() Console{
   return &console{}
}

Now when I use this somewhere I end up using a console.Console type everywhere.

When I have two or more structs in a package I end up things like
con := console.NewConsole()

I don't mind having large mostly flat package structures but I do like to keep my code organized as much as possible. I am ok with the idea of IO.Reader and IO.Writer but what to do when the package is the same as the thing but still needs to be separated. (Yes I am aware that the given example could be Console.Writer but lets pretend its something completely different)

So my questions are:
Is this stutter effect something I should even worry about? (ie. Is it bad form?)
Does anyone have any tips in avoiding it?

答案1

得分: 28

类型名称的重复是可以接受的——拥有 foo.Foo 这样的命名并不罕见,因为 foo 包专门用于定义 Foo 类型。这样做没有任何问题。

你需要避免的是不必要的重复;比如,当仅仅使用 foo.New 就足够准确时,不要使用 foo.NewFoo;或者当 foo.Barfoo.Baz 同样适用时,不要使用 foo.FooBarfoo.FooBaz

可以考虑一下标准库中的 html/template,它定义了一个类型 (template.Template) 和一个构造函数 (template.New)。

英文:

Stuttering type names are generally fine - it's not unusual to have a foo.Foo, because package foo is dedicated to defining type Foo. There's absolutely nothing wrong with that.

What you want to avoid is unnecessary stuttering; this would be things like foo.NewFoo when simply foo.New is sufficiently precise, or foo.FooBar and foo.FooBaz where foo.Bar and foo.Baz would work just as well.

Consider the standard library's html/template, which defines a type (template.Template) and a constructor (template.New).

huangapple
  • 本文由 发表于 2017年8月26日 00:40:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/45885985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定