Method chaining in Golang

By yuseferi, 28 January, 2022
method chaining in Golang

Although it's not an idiom in Golang to do method changing in some cases that would be useful if you chain your method.

The reason behind it why it's not idiomatic is different exception handling, in another programming language in terms of exceptions in one of the chan functions it throws the exception and other methods won't get run. 
in this article, I'm going to show how we can implement it in Golang. 

let's suppose that I want to have an app registry that wanted to add clients dynamically, 

package main

import (
	"errors"
	"fmt"
	"log"
)

type (
	ClientA struct {
	}
	ClientB struct {
	}
	ClientC struct {
	}
)
type Registry struct {
	ca  *ClientA
	cb  *ClientB
	cc  *ClientC
	err error
}

func (r *Registry) withClientA() *Registry {
	if r.err != nil {
		return r
	}
	fmt.Println("client A initialed")
	r.ca = &ClientA{}
	return r
}
func (r *Registry) withClientB() *Registry {
	if r.err != nil {
		return r
	}
	r.err = errors.New("error at initial client B")
	return r
}
func (r *Registry) withClientC() *Registry {
	if r.err != nil {
		return r
	}
	fmt.Println("client C initialed")
	r.cc = &ClientC{}
	return r
}

func main() {
	c := Registry{}
	d := c.withClientA().withClientB().withClientC()
	if d.err != nil {
		log.Fatalf("can not initial Clients due to %v", d.err)
	}
}

Playground 
if you run it you can see, du to an intentional error on ClientB initialization, the chain of methods will be failed and error would be catched in the registry.