I always struggle with naming. And I am not the only one. I know this from my experiences with code reviews and so on.
Here are some nice examples (mainly in golang and most of these are taken from https://google.github.io/styleguide/go/decisions#variable-names):
"Repetitive name" to "Better name"
Repetitive name -> better name
widget.NewWidget -> widget.New
widget.NewWidgetWithName -> widget.NewWithName
db.LoadFromDatabase -> db.Load
goatteleportutil.CountGoatsTeleported -> gtutil.CountGoatsTeleported or goatteleport.Count
myteampb.MyTeamMethodRequest -> mtpb.MyTeamMethodRequest or myteampb.MethodRequest
var numUsers int -> var users int //the variable type int already tells that users is a number, so no need to add the prefix`num`. Similar are true for the below examples
var nameString string -> var name string
var primaryProject *Project -> var primary *Project
More examples with package/lib
// In package "ads/targeting/revenue/reporting"
//bad
type AdsTargetingRevenueReport struct{}
//good
type Report struct{}
// In package "sqldb"
// bad:
type DBConnection struct{}
//good
type Connection struct{}
Short variable
I usually write long variable names. But, for the following cases a short variable name is a better choice:
- for common types
r = io.reader
w = io.writer
- inside a loop
for i = 0; ...
- When the scope of the variable is short, then use short variable name. If the scope of the variable is long, then use longer variable name (Uncle Bob)
Reference
Almost all the examples are taken from https://google.github.io/styleguide/go/decisions#variable-names
Recent Comments