Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go idiomatic way to name boolean predicate functions

Tags:

go

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?

like image 708
Lee Avatar asked Jan 05 '14 14:01

Lee


People also ask

How do you name a boolean function?

The usual convention to name methods that return boolean is to prefix verbs such as 'is' or 'has' to the predicate as a question, or use the predicate as an assertion. For example, to check if a user is active, you would say user. isActive() or to check if the user exists, you would say user. exists().

How do you name Booleans in Python?

There is no standard naming convention specific to boolean-returning methods. However, PEP8 does have a guide for naming functions. Function names should be lowercase, with words separated by underscores as necessary to improve readability.


1 Answers

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.

like image 192
rancidfishbreath Avatar answered Oct 03 '22 22:10

rancidfishbreath