Better Examples

Observation of some great examples in docs

In this post we’ll talk about creating good examples. More effort should go into writing good examples. Any Codebase or API that lacks examples is usually harder to understand and integrate with.

When creating a new function or api one might assume that the caller of that api is very familiar with it. This assumption can lead to friction and potentially make it more difficult for the consumer. A good interface should assume the caller has as little understanding as possible.

The go ecosystem contains some examples where documentation is easy to consume and learn from.

Let’s show an example from the fmt package explaining fmt.FprintF. This example is taken from here. I’ve also added the go doc string below.

Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.

func main() {
    const name, age = "Kim", 22
    n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")

    // The n and err return values from Fprint are
    // those returned by the underlying io.Writer.
    if err != nil {
    fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
    }
    fmt.Print(n, " bytes written.\n")
}
Output:

Kim is 22 years old.
21 bytes written.

This example does multiple things well. It explains what it’s going to do with your input and it explains how it’s going to respond. I don’t think you’ll need to jump inside of that function to read it’s implementation any time soon.

In an ideal world you’d have an interface that callers could intuitively understand and utilize with minimal effort.

Here’s a fantastic resource that I used early on in my career to learn go. gobyexample.com

← Back to Posts

#Golang   #Docs