This is a continuation of the common design patterns I found in my old code series, which I started in a previous post.
Another common pattern I found is the factory method pattern, which is a design pattern used to create different types of objects using the same interface.
This pattern is actually pretty common in Go. Some good example of this are the builtin I/O libraries:
package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"os"
)
func main() {
f, _ := os.Open("avengers.csv")
records, _ := parseCsv(f)
fmt.Println("Records from file", records)
data := []byte("name,surname\nJohn,Snow\n")
r := bytes.NewReader(data)
records, _ = parseCsv(r)
fmt.Println("Records from bytes", records)
}
func parseCsv(r io.Reader) ([][]string, error) {
cr := csv.NewReader(r)
return cr.ReadAll()
}
Both the bytes.NewReader() and os.Open() implement the io.Reader interface which comes in handy for the parseCsv() method above as we can use it to parse data from multiple sources.