Lee
Lee

Reputation: 8734

Go idiomatic way to name boolean predicate functions

Lets say you are working with a func that returns a bool as to whether a user has been active in the last month.

In Ruby:

def active_in_last_month?;end

In C#

public bool WasActiveInLastMonth(){}

What is the idiomatic way of naming boolean predicate functions in Go?

Upvotes: 20

Views: 13630

Answers (1)

rancidfishbreath
rancidfishbreath

Reputation: 3994

tl;dr

func wasActiveInLastMonth() bool

Full Answer

I looked in the GitHub repos of some well known open source projects, picked a semi-random file, and found the following:

Etcd lease/lessor.go

func (le *lessor) isPrimary() bool

Kubernetes service/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

Consul agent/acl.go

func (m *aclManager) isDisabled() bool

Docker Moby (open source upstream of Docker) cli/cobra.go

func hasSubCommands(cmd *cobra.Command) bool

func hasManagementSubCommands(cmd *cobra.Command) bool

I would say that these four projects represent some of the most well reviewed and famous go code in existence. It seems that the is/has pattern is very prevalent although not the only pattern. If you choose this pattern you will certainly be able to defend your choice as a de facto idiom.

Upvotes: 15

Related Questions