talks/2014/names: revise slides on local variables I was overzealous about short local variable names. On reflection I think my advice was too strong, and the example I gave was hard even for me to read. Change-Id: I3c300b95ac0453b9b5d1cfcd1e167965b643c817 Reviewed-on: https://go-review.googlesource.com/78135 Reviewed-by: Rob Pike <r@golang.org>
diff --git a/2014/names.slide b/2014/names.slide index 199a7fa..6ba39ba 100644 --- a/2014/names.slide +++ b/2014/names.slide
@@ -8,9 +8,6 @@ https://golang.org/ -* An old joke - - * Names matter Readability is the defining quality of good code. @@ -48,45 +45,54 @@ Keep them short; long names obscure what the code _does_. +Common variable/type combinations may use really short names: + Prefer `i` to `index`. Prefer `r` to `reader`. +Prefer `b` to `buffer`. + +Avoid redundant names, given their context: + +Prefer `count` to `runeCount` inside a function named `RuneCount`. +Prefer `ok` to `keyInMap` in the statement + + v, ok := m[k] Longer names may help in long functions, or functions with many local variables. - (But often this just means you should refactor.) * Bad func RuneCount(buffer []byte) int { - index, count := 0, 0 - for index < len(buffer) { + runeCount := 0 + for index := 0; index < len(buffer); { if buffer[index] < RuneSelf { index++ } else { _, size := DecodeRune(buffer[index:]) index += size } - count++ + runeCount++ } - return count + return runeCount } * Good func RuneCount(b []byte) int { - i, n := 0, 0 - for i < len(b) { + count := 0 + for i := 0; i < len(b); { if b[i] < RuneSelf { i++ } else { - _, size := DecodeRune(b[i:]) - i += size + _, n := DecodeRune(b[i:]) + i += n } - n++ + count++ } - return n + return count }