What are some best practices to follow when naming variables?
What are some rec开发者_如何学Pythonommended best practices to follow when naming variables? Global variables?
When working with a solution having many projects, insure that all public names indicate a relevant context. Do not use identical names in different projects. Compilation works but maintenance can be a nightmare.
To a large extent it does not matter what standards you decide to adopt. The most important factor is that you stick to it! Consistency is really important and as long as you manage that your code will be significantly easier to read and maintain in the future.
As one idea you could check out the hungarian notation used for Win32 and C++ programming under windows.
Notation Definition (PDF)
Keep your names meaningful, the code should self document, avoid abbreviations the length of the name isn't usually a problem in most languages.
Boolean variables should begin is*
or has*
, try to choose a name that avoids requiring negation in tests as the !
can often be missed.
Group variables associated with an item by using a common prefix i.e. documentTitle
, documentType
, documentSize
etc.
Avoid using numbers to distinguish variables unless an index is involved.
Forget about Hungarian notation.
Some broad strokes:
- Use
i
,j
,k
for loop variables. It's very common practice and easy to understand. - For boolean (true/false) variables, use predicate names like
isDirectory
orcanExecute
. - Whether you
camelCase
oruse_underscores
is just a matter of preference. - It may be a good idea to decorate variables with Hungarian notation describing the meaning of the variable, e.g.
iMax
could be the index of the maximum element in an array. It's less useful to decorate names with the language-level type information. For a very entertaining explanation of the difference, and why one is good and the other bad, see Joel's essay.
Best to not start them with numbers or symbols in some languages. Also, don't use reserved functions of the language you're using. For example: in C# you wouldn't want to name it "if", "else", "void" "try" etc...
I'm by no means an experienced programmer, but I've somewhat had it drilled into me at college and uni, and have seen it on sites like this, that when naming variables they should mean something.
Maybe this is an education thing, but it does make sense - the variable name should make it easily apparent what that variable is used for, anywhere in your code. It comes down to, I think, the fact that code shouldn't need masses of comments - it should explain itself. Variable naming is a part of that.
精彩评论