DISCLAIMER: This has nothing to do with a certain famous book that also speaks about Clean Code. Nothing. I’m talking from the experience of writing lots of bad code throughout the years, of lots of research on how to do it better while writing Go code and these examples do not necessarily apply to any other programming language.

This is the third post of a series that started here based on a talk I gave about Go and Clean Code(slides here, in Portuguese).

I’d like to explore a bit more on the unpopular art of naming functions and interfaces. I am gonna introduce these things very quickly, then I’m gonna talk about a couple of naming conventions for then, and provide a couple of examples alongside with a brief explanation of these examples. As usual, I will provide links to my references.

We’ll always use mixedCaps or MixedCaps, depending on whether we want to export a name or not.

The basic rules of naming things should be applied here: be concise, be descriptive. Pick short and meaningful names.

Functions

Functions in Go are like functions in pretty much every programming language. They do something given a specific numbers of arguments and may or may not return values. They can be simple functions, have multiple return values, they can be variadic function, recursive functions or even anonymous functions also known as closures.

Getters and Setters

It is very common, in several languages, to write getters and setters for properties that are not exported or that require a special treatment.

In Go, if we want to get the owner property of an object, this is how we want to do it:

199
obj.Owner()

But if we want to set the owner property, we want to do:

199
obj.SetOwner(owner)

The most shockingly news about this approach is the lack of the word get on the getter. Its use is discouraged by Effective Go

Interfaces

An Interface type holds a set of method signatures. Go has thing very cool thing that for a thing to be of the same type of an Interface, it doesn’t have to explicitly reference it - following the same set of method signatures is enough!

We often want to keep our interfaces tiny and with a very clear purpose. Right? I’m judging you if you make your interfaces do more than one thing, but don’t be mistaken, I do it more often than I’d like to admit.

When we have interfaces that have only one method, we adopt, by convention, the name of the method + the suffix -er. The following interface names are pretty dope:

  • Reader
  • Writer
  • Formatter
  • Notifier

They normally look like that:

199
200
201
202
203
204
205
type Caller interface {
	Call()
}

type Notifier interface {
	Notify()
}

“Sometimes the result isn’t correct English, but we do it anyway. Sometimes we use English to make it nicer.” - Andrew Gerrand, What’s in a name?

Cool reference links

Past Posts