Empty string check #3

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

Do this:

if s == "" {
	...
}

Don't do this:

if len(s) == 0 {
	...
}

If you're checking if s is the empty string. Using len(s) is fine for other uses.

The first form is more readable because it's more obvious s is a string and not a slice.

See Russ Cox's comment in a golang-nuts thread:

if I care about "is it this specific string" I tend to write s == "".

Write Preview Markdown
xlab commented 8 years ago

I see no reason making obvious the difference between string and []byte, moreover, they are quite interchangeable.

From Go spec:

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array.

A string value is a (possibly empty) sequence of bytes.

Consider refactoring of this piece of code. First case: you need to slightly adjust the rule, mark strings as empty if they have less than 2 char. With "incorrect" case you'll simply change the rule, in the "correct" case you'll rewrite the whole sentence. Switching back is pain too.

Second case: change string to []byte while doing performance improvement refactoring. In the "incorrect" form of they are interchangeable, in the "correct" form they are not, and you are forced to redo the whole check..

These are small quirks, but the string length checking may occur in many places. Using the "correct" form is like throwing small rocks on the road in front of a cyclist.

Write Preview Markdown
dmitshur commented 8 years ago · edited

Hey @xlab, thanks for providing some rationale why you think the opposite is a better style. Although I found the reactions quite fun too. :P

I'll think some about this and get back to you.

It's also going to be helpful to look around more Go standard library code and see what's being done there.

Write Preview Markdown
to comment.