Sunday, October 12, 2025
HomeGolangDecreasing nil test test boilerplate - Getting Assist

Decreasing nil test test boilerplate – Getting Assist


Hey of us,

I’ve received numerous features that get handed in some interface for working on and should do nil checks first:

func F(foo MyInterface, …) (one thing, error) {
if foo == nil {
return ErrParamNil
}

}

Is there any good manner for lowering the boilerplate right here ?

thx.

Often one would suggest towards doing this.
It’s merely a Go-idiom with the philosophy that it is best to do one thing smart along with your errors on the place they happen.

For instance:

Within the code-generator utility github.com/spf13/cobra-cli (which is personally not my favourite as a result of I believe it’s a bit bloated) which generates code that the github.com/spf13/cobra-library makes use of (“for all of your CLI-needs”), we are able to discover this operate:

func CheckErr(msg interface{}) {
	if msg != nil {
		fmt.Fprintln(os.Stderr, "Error:", msg)
		os.Exit(1)
	}
}

I wouldn’t suggest precisely copying this however there are very artistic methods to deal with errors. I’m all the time curious to study attention-grabbing methods completely different initiatives use errors, do some other individuals know good examples?

Since I used to be making an attempt out the most recent model of cobra myself whereas penning this publish, I’ll simply depart the steps right here:

  • go get github.com/spf13/cobra-cli@newest
  • mkdir work
  • cd work
  • cobra-cli assist
  • cobra-cli init --pkgname mymymynick/mycobracliapp
  • cd mycobracliapp
  • test the generated code in root.go the place the cobra.CheckErr-function is named
  • cobra add newcommand
  • the file work/mycobracliapp/cmd/newcommand.go is now created and you may add your personal code within the Run-field of the cobra.Command-struct-literal. This code can be ran while you …
  • go construct
  • ./mycobracliapp newcommand

Right here’s a easy instance straight from the usual library docs (https://pkg.go.dev/html/template).

It’s helpful if you wish to outline an error handler domestically in a operate.
That is accomplished by assigning an nameless operate func(err error) to the test-variable. (Which is feasible due to Go supporting features as values.)

func funcWithLocallySpecificErrorHandlingButUsedMultipleTimes() {	
	test := func(err error) {
			if err != nil {
				log.Deadly(err)
			}
		}

    _, err := errorReturningFunc()
    test(err)
    _, err := anotherErrorreturningFunc()
    test(err)
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments