Error variable naming #9

Opendmitshur opened this issue 9 years ago
dmitshur commented 9 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://go.dev/talks/2014/names.slide#14.

Write Preview Markdown
storozhukBM commented 7 years ago

specificErr seems more reasonable.

Write Preview Markdown
dmitshur commented 7 years 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 7 years 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 7 years 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
QuantumGhost commented 10 months ago

IMO, use const for exported sentinel errors is much better.

type sentinel string

func (s sentinel) Error() string {
	return string(s)
}

const (
	ErrorSomething sentinel = "something wrong"
)
Write Preview Markdown
to comment.