在为一个函数或方法选择名称时,要考虑该名称将被阅读的环境。请考虑以下建议,以避免在调用地点出现过多的重复:
以下内容一般可以从函数和方法名称中省略。
对于函数,不要重复软件包的名称。
1. `// Bad:`
2. `package yamlconfig`
3. ``
4. `func ParseYAMLConfig(input string) (*Config, error)`
对于方法不要重复方法接收器的名称。
// Bad:
func (c *Config) WriteConfigTo(w io.Writer) (int64, error)
// Good:
func (c *Config) WriteTo(w io.Writer) (int64, error)
不要重复传参的变量名称
// Bad:
func TransformYAMLToJSON(input *Config) *jsonconfig.Config
// Good:
func Transform(input *Config) *jsonconfig.Config
当有必要区分类似名称的函数时,包含额外信息是可以接受的。
// Good:
func (c *Config) WriteTextTo(w io.Writer) (int64, error)
func (c *Config) WriteBinaryTo(w io.Writer) (int64, error)
在为函数和方法选择名称时,还有一些常见的约定:
// Good:
func (c *Config) JobName(key string) (value string, ok bool)
这方面的一个推论是,函数和方法名称应该避免使用前缀Get。
// Bad:
func (c *Config) GetJobName(key string) (value string, ok bool)
// Good:
func (c *Config) WriteDetail(w io.Writer) (int64, error)
// Good:
func ParseInt(input string) (int, error)
func ParseInt64(input string) (int64, error)
func AppendInt(buf []byte, value int) []byte
func AppendInt64(buf []byte, value int64) []byte
如果有一个明确的 “主要 “版本,该版本的名称中可以省略类型:
// Good:
func (c *Config) Marshal() ([]byte, error)
func (c *Config) MarshalText() (string, error)