Error variable naming #9

Opendmitshur opened this issue 2 years ago
dmitshur commented 2 years ago · edited

Do this:

// Package level exported error.
var ErrSomething = errors.New("something went wrong")

func main() {
	// Normally you call it just "err",
	result, err := doSomething()
	// and use err right away.

	// But if you want to give it a longer name, use "somethingError".
	var specificError error
	result, specificError = doSpecificThing()

	// ... use specificError later.
}

Don't do this:

var ErrorSomething = errors.New("something went wrong")
var SomethingErr = errors.New("something went wrong")
var SomethingError = errors.New("something went wrong")

func main() {
	var specificErr error
	result, specificErr = doSpecificThing()

	var errSpecific error
	result, errSpecific = doSpecificThing()

	var errorSpecific error
	result, errorSpecific = doSpecificThing()
}

For consistency. See https://talks.golang.org/2014/names.slide#14.

Write Preview Markdown
storozhukBM commented 10 months ago

specificErr seems more reasonable.

Write Preview Markdown
dmitshur commented 10 months ago · edited

@storozhukBM I guess both are fair style choices. I wanted to pick one, so that all my code would be consistent. specificError seemed more natural to me: if the first word is long and written in full, might as well write "Error" in full too.

Write Preview Markdown
storozhukBM commented 10 months ago · edited

@shurcooL I always use specific names for errors, so compiler can help me to detect not checked ones, as not used variables.

Write Preview Markdown
dmitshur commented 10 months ago

That's an interesting approach. I haven't seen that before. Thanks for sharing.

I know there are tools such as errcheck and staticcheck that can help detect unchecked errors even if you reuse the same err variable.

Write Preview Markdown
to comment.