以惯用的方式命名布尔谓词函数

Lee*_*Lee 11 go

假设您正在使用一个函数来返回一个bool,以确定用户是否在上个月处于活动状态.

在Ruby中:

def active_in_last_month?;end
Run Code Online (Sandbox Code Playgroud)

在C#中

public bool WasActiveInLastMonth(){}
Run Code Online (Sandbox Code Playgroud)

在Go中命名布尔谓词函数的惯用方法是什么?

ran*_*ath 8

tl;博士

func wasActiveInLastMonth() bool
Run Code Online (Sandbox Code Playgroud)

完整答案

我查看了一些知名开源项目的 GitHub 存储库,选择了一个半随机文件,发现以下内容:

Etcd 租赁/出租人.go

func (le *lessor) isPrimary() bool
Run Code Online (Sandbox Code Playgroud)

Kubernetes 服务/service_controller.go

func (s *ServiceController) needsUpdate(oldService *v1.Service, newService *v1.Service) bool

func portsEqualForLB(x, y *v1.Service) bool

func portSlicesEqualForLB(x, y []*v1.ServicePort) bool
Run Code Online (Sandbox Code Playgroud)

领事代理/acl.go

func (m *aclManager) isDisabled() bool
Run Code Online (Sandbox Code Playgroud)

Docker Moby(Docker 上游开源)cli/cobra.go

func hasSubCommands(cmd *cobra.Command) bool

func hasManagementSubCommands(cmd *cobra.Command) bool
Run Code Online (Sandbox Code Playgroud)

我想说这四个项目代表了现存的一些最受好评和最著名的 Go 代码。似乎 is/ha 模式非常普遍,但不是唯一的模式。如果您选择这种模式,您当然可以将您的选择作为事实上的习语进行辩护。

  • go源代码本身使用“is”:https://golang.org/src/go/types/predicates.go (2认同)

Vor*_*ung -2

Donovan 和 Kernighan 所著的《The Go 编程语言》在第 6 章中建议:

仅访问或修改类型的内部值的函数称为 getter 和 setter。然而,在命名 getter 方法时,我们通常省略 Get 前缀。为了简洁起见,这种偏好扩展到所有方法,而不仅仅是字段访问器,还扩展到其他还原前缀,例如 Fetch、Find 和 Lookup

根据这个建议,我会将函数命名为“LastMonth”或“lastMonth”(如果它是包私有的)以跳过前缀