Always be thinking about it whenever you write or read code, including other people's code. Try to figure out what you would do differently in their code and talk to them about it, when possible (but don't harp on it, that would be a nuisance). Ask them questions about why they picked a certain name.
See how well your code reads without comments. If you ever need to comment on the basic purpose of something you named, consider whether it could have a better name.
The biggest thing is active mental participation: practice.
Thinking of names seems to be something that some people are extraordinarily bad at, and I'm not sure what the cure is. Back when I was an instructor working in commercial training, I'd often see situations like this:
Me: OK, now you need to create an integer variable to contain the value returned by getchar().
[Trainees start typing, and I wander round the training room. Most are doing fine, but one is sitting like a deer frozen the headlights]
Me: What's the problem?
Him: I can't think of a name for the variable!
So, I'd give them a name for it, but I have a feeling that people with this problem are not going to go far in programming. Or perhaps the problem is they go too far...
I strive to make my code align with the libraries (or, at the least the standard ones) so that the code has an uniformity. I'd suggest: See how the standard library functions are named. Look for patterns. Learn what different naming conventions exist. See which one makes the most sense. E.g: most Java code uses really big identifier names, Camel casing etc. C uses terse/short names. There is then the Hungarian notation -- which was worth the trouble when editors weren't smart enough to provide you with type information. Nowadays, you probably don't need it.
Let’s try to come up with a coding convention that will ensure that if you ever make this mistake, the code will just look wrong. If wrong code, at least, looks wrong, then it has a fighting chance of getting caught by someone working on that code or reviewing that code.
He goes on to show how naming variables in a rigourous fashion can improve our code. The point being, that avoiding bugs has a quicker and more obvious ROI than making our code more "maintainable".
A good way to find expressive names is starting with a textual description what your piece of software actually does. Good candidates for function (method) names are verbs, for classes nouns. If you do design first, one method is textual analysis.
对于 Visual Studio 中的 C#、C++、C,请尝试使用 AtomineerUtils 向方法添加文档注释,该工具会根据您的名称自动生成文档,因此您的名称越好,文档就越好,完成文档所需的工作量就越少。
(Even if you are only a team of 1) agree a coding standard with your colleagues so you all use the same conventions for naming. (e.g. It is common to use properties for values that are returned quickly, but a GetXXX or CalculateXXX method for values that will take time to calculate. This convention gives the caller a much better idea about whether they need to cache the results etc). Try to use the same names for equivalent concepts (e.g. Don't mix Array.Count and List.Length as Microsoft did in .net!)
Try to read your code as if somebody else wrote it (i.e. forget everything you know and just read it). Does it make sense? Does it explain everything they need to know to understand it? (Probably not, because we all forget to describe the stuff we "know" or which is "obvious". Go back and clarify the naming and documentation so that someone else can pick up your code file and easily understand it)
Keep names short but descriptive. There is no point writing a whole sentence, but with auto-completion in most IDEs, there is also little point in abbreviating anything unless it's a very standard abbreviation.
Don't waste characters telling somebody that this string is a string (the common interpretation of hungarian notation). Use names that describe what something does, and how it is used. e.g. I use prefixes to indicate the usage (m=member, i=iterator/index, p=pointer, v=volatile, s=static, etc). This is important information when accessing the variable so it's a useful addition to the name. It also allows you to copy a line of code into an email and the receiver can understand exactly what all the variables are meant to do - the difference in usage between a static volatile and a parameter is usually very important.
Describe the contents of a variable or the purpose of a method in its name, avoiding technical terms unless you know that all the readers of your code will know what those terms mean. Use the simplest description you can think of - complex words and technical terms sound intelligent and impressive, but are much more open to misinterpretation (e.g. off the top of my head: Collation or SortOrder, Serialise or Save - though these are well known words in programming so are not very good cases).
Avoid vague and near-meaningless terms like "value", "type". This is especially true of base class properties, because you end up with a "Type" in a derived class and you have no idea what kind if type it is. Use "JoystickType" or "VehicleType" and the meaning is immediately much clearer.
If you use a value with units, tell people what they are in the name (angleDegrees rather than angle). This simple trick will stop your spacecraft smashing into Mars.
For C#, C++, C in Visual Studio, try using AtomineerUtils to add documentation comments to methods, classes etc. This tool derives automatic documentation from your names, so the better your names are, the better the documentation is and the less effort you need to put in the finish the documentation off.
Read "Code Complete" book, more specifically Chapter 11 about Naming. This is the checklist (from here, free registration required):
General Naming Considerations
Does the name fully and accurately describe what the variable represents? Does the name refer to the real-world problem rather than to the programming-language solution? Is the name long enough that you don't have to puzzle it out? Are computed-value qualifiers, if any, at the end of the name? Does the name use Count or Index instead of Num?
Naming Specific Kinds Of Data
Are loop index names meaningful (something other than i, j, or k if the loop is more than one or two lines long or is nested)? Have all "temporary" variables been renamed to something more meaningful? Are boolean variables named so that their meanings when they're True are clear? Do enumerated-type names include a prefix or suffix that indicates the category-for example, Color_ for Color_Red, Color_Green, Color_Blue, and so on? Are named constants named for the abstract entities they represent rather than the numbers they refer to?
Naming Conventions
Does the convention distinguish among local, class, and global data? Does the convention distinguish among type names, named constants, enumerated types, and variables? Does the convention identify input-only parameters to routines in languages that don't enforce them? Is the convention as compatible as possible with standard conventions for the language? Are names formatted for readability?
Short Names
Does the code use long names (unless it's necessary to use short ones)? Does the code avoid abbreviations that save only one character? Are all words abbreviated consistently? Are the names pronounceable? Are names that could be mispronounced avoided? Are short names documented in translation tables?
Common Naming Problems: Have You Avoided...
...names that are misleading? ...names with similar meanings? ...names that are different by only one or two characters? ...names that sound similar? ...names that use numerals? ...names intentionally misspelled to make them shorter? ...names that are commonly misspelled in English? ...names that conflict with standard library-routine names or with predefined variable names? ...totally arbitrary names? ...hard-to-read characters?
发布评论
评论(8)
实践。
每当您编写或阅读代码(包括其他人的代码)时,请始终考虑它。尝试弄清楚你会在他们的代码中做哪些不同的事情,并在可能的情况下与他们讨论(但不要喋喋不休,那会很麻烦)。询问他们为什么选择某个名字。
查看您的代码在没有注释的情况下可读性如何。如果您需要评论您所命名的事物的基本用途,请考虑是否可以有一个更好的名称。
最重要的是积极的心理参与:练习。
Practice.
Always be thinking about it whenever you write or read code, including other people's code. Try to figure out what you would do differently in their code and talk to them about it, when possible (but don't harp on it, that would be a nuisance). Ask them questions about why they picked a certain name.
See how well your code reads without comments. If you ever need to comment on the basic purpose of something you named, consider whether it could have a better name.
The biggest thing is active mental participation: practice.
想名字似乎是有些人非常不擅长的事情,我不知道治愈方法是什么。当我还是一名从事商业培训的讲师时,我经常会看到这样的情况:
我:好的,现在您需要创建一个整数变量来包含 getchar() 返回的值。
[学员开始打字,我在培训室里闲逛。大多数人都很好,但有一个人像鹿一样坐在那里,车头灯被冻住了]
我:有什么问题吗?
他:我想不出变量的名字!
所以,我会给他们一个名字,但我有一种感觉,有这个问题的人不会在编程方面走得太远。或者也许问题是他们走得太远了......
Thinking of names seems to be something that some people are extraordinarily bad at, and I'm not sure what the cure is. Back when I was an instructor working in commercial training, I'd often see situations like this:
Me: OK, now you need to create an integer variable to contain the value returned by getchar().
[Trainees start typing, and I wander round the training room. Most are doing fine, but one is sitting like a deer frozen the headlights]
Me: What's the problem?
Him: I can't think of a name for the variable!
So, I'd give them a name for it, but I have a feeling that people with this problem are not going to go far in programming. Or perhaps the problem is they go too far...
这是一个主观问题。
我努力使我的代码与库(或者至少是标准库)保持一致,以便代码具有统一性。我建议:看看标准库函数是如何命名的。寻找模式。了解存在哪些不同的命名约定。看看哪一个最有意义。例如:大多数 Java 代码使用非常大的标识符名称、驼峰式大小写等。C 使用简洁/短名称。然后是匈牙利表示法——当编辑器不够聪明无法为您提供类型信息时,这是值得的。如今,您可能不需要它。
This is a subjective question.
I strive to make my code align with the libraries (or, at the least the standard ones) so that the code has an uniformity. I'd suggest: See how the standard library functions are named. Look for patterns. Learn what different naming conventions exist. See which one makes the most sense. E.g: most Java code uses really big identifier names, Camel casing etc. C uses terse/short names. There is then the Hungarian notation -- which was worth the trouble when editors weren't smart enough to provide you with type information. Nowadays, you probably don't need it.
Joel Spolsky 撰写了一篇关于匈牙利表示法的有用文章几年前。他的主要见解是:
他接着展示了如何以严格的方式命名变量来改进我们的代码。重点是,避免错误比让我们的代码更“可维护”具有更快、更明显的投资回报率。
Joel Spolsky wrote a helpful article on Hungarian notation a few years back. His key insight is this:
He goes on to show how naming variables in a rigourous fashion can improve our code. The point being, that avoiding bugs has a quicker and more obvious ROI than making our code more "maintainable".
阅读一些好的代码并模仿它。这是学习任何东西的通用方法;只需用适当的单词替换“阅读”和“代码”即可。
Read some good code and imitate it. That's the universal way of learning anything; just replace "read" and "code" with appropriate words.
找到富有表现力的名称的一个好方法是从文本描述您的软件的实际功能开始。
函数(方法)名称的最佳候选者是动词,类名词的最佳候选者是动词。
如果您首先进行设计,一种方法是文本分析。
A good way to find expressive names is starting with a textual description what your piece of software actually does.
Good candidates for function (method) names are verbs, for classes nouns.
If you do design first, one method is textual analysis.
(即使你们只有 1 人的团队)与同事达成一致的编码标准,以便你们都使用相同的命名约定。 (例如,通常对快速返回的值使用属性,但对需要时间计算的值使用 GetXXX 或CalculateXXX 方法。此约定使调用者可以更好地了解是否需要缓存结果等)。尝试对等效概念使用相同的名称(例如,不要像 Microsoft 在 .net 中那样混合使用 Array.Count 和 List.Length!)
尝试像其他人编写代码一样阅读您的代码(即忘记您所知道的一切)并阅读它)。有道理吗?它是否解释了他们需要了解的一切以理解它? (可能不是,因为我们都忘记描述我们“知道”或“显而易见”的东西。返回并澄清命名和文档,以便其他人可以拿起您的代码文件并轻松理解它)
保留名称简短但具有描述性。编写整个句子是没有意义的,但由于大多数 IDE 都具有自动完成功能,因此缩写任何内容也没有什么意义,除非它是非常标准的缩写。
不要浪费字符告诉别人这个字符串是一个字符串(匈牙利表示法的常见解释)。使用描述某事物做什么以及如何使用的名称。例如,我使用前缀来指示用法(m=成员、i=迭代器/索引、p=指针、v=易失性、s=静态等)。这是访问变量时的重要信息,因此它是对名称的有用补充。它还允许您将一行代码复制到电子邮件中,并且接收者可以准确理解所有变量的用途 - 静态易失性和参数之间的用法差异通常非常重要。
在变量名称中描述变量的内容或方法的用途,避免使用技术术语,除非您知道代码的所有读者都会知道这些术语的含义。使用您能想到的最简单的描述 - 复杂的单词和技术术语听起来聪明且令人印象深刻,但更容易被误解(例如,我突然想到:排序规则或排序顺序,序列化或保存 - 尽管这些是众所周知的单词)编程这样不是很好的情况)。
避免模糊且近乎无意义的术语,例如“值”、“类型”。对于基类属性尤其如此,因为您最终会在派生类中得到一个“类型”,并且您不知道它是什么类型。使用“JoystickType”或“VehicleType”,含义立即变得更加清晰。
如果您使用带有单位的值,请告诉人们名称中的含义(角度而不是角度)。这个简单的技巧将阻止您的航天器撞上火星。
对于 Visual Studio 中的 C#、C++、C,请尝试使用 AtomineerUtils 向方法添加文档注释,该工具会根据您的名称自动生成文档,因此您的名称越好,文档就越好,完成文档所需的工作量就越少。
(Even if you are only a team of 1) agree a coding standard with your colleagues so you all use the same conventions for naming. (e.g. It is common to use properties for values that are returned quickly, but a GetXXX or CalculateXXX method for values that will take time to calculate. This convention gives the caller a much better idea about whether they need to cache the results etc). Try to use the same names for equivalent concepts (e.g. Don't mix Array.Count and List.Length as Microsoft did in .net!)
Try to read your code as if somebody else wrote it (i.e. forget everything you know and just read it). Does it make sense? Does it explain everything they need to know to understand it? (Probably not, because we all forget to describe the stuff we "know" or which is "obvious". Go back and clarify the naming and documentation so that someone else can pick up your code file and easily understand it)
Keep names short but descriptive. There is no point writing a whole sentence, but with auto-completion in most IDEs, there is also little point in abbreviating anything unless it's a very standard abbreviation.
Don't waste characters telling somebody that this string is a string (the common interpretation of hungarian notation). Use names that describe what something does, and how it is used. e.g. I use prefixes to indicate the usage (m=member, i=iterator/index, p=pointer, v=volatile, s=static, etc). This is important information when accessing the variable so it's a useful addition to the name. It also allows you to copy a line of code into an email and the receiver can understand exactly what all the variables are meant to do - the difference in usage between a static volatile and a parameter is usually very important.
Describe the contents of a variable or the purpose of a method in its name, avoiding technical terms unless you know that all the readers of your code will know what those terms mean. Use the simplest description you can think of - complex words and technical terms sound intelligent and impressive, but are much more open to misinterpretation (e.g. off the top of my head: Collation or SortOrder, Serialise or Save - though these are well known words in programming so are not very good cases).
Avoid vague and near-meaningless terms like "value", "type". This is especially true of base class properties, because you end up with a "Type" in a derived class and you have no idea what kind if type it is. Use "JoystickType" or "VehicleType" and the meaning is immediately much clearer.
If you use a value with units, tell people what they are in the name (angleDegrees rather than angle). This simple trick will stop your spacecraft smashing into Mars.
For C#, C++, C in Visual Studio, try using AtomineerUtils to add documentation comments to methods, classes etc. This tool derives automatic documentation from your names, so the better your names are, the better the documentation is and the less effort you need to put in the finish the documentation off.
阅读“Code Complete”一书,更具体地说是有关命名的第 11 章。这是清单(来自此处,需要免费注册):
常规命名注意事项
名称是否完整、准确地描述了变量所代表的含义?
该名称是否指的是现实世界的问题而不是编程语言的解决方案?
这个名字足够长以至于你不必费力去猜吗?
名称末尾是否有计算值限定符(如果有)?
名称是否使用 Count 或 Index 而不是 Num?
命名特定类型的数据
循环索引名称是否有意义(如果循环长度超过一两行或者是嵌套的,则为 i、j 或 k 以外的名称)?
所有“临时”变量是否都已重命名为更有意义的名称?
布尔变量的命名是否使得它们为 True 时的含义清晰?
枚举类型名称是否包含指示类别的前缀或后缀,例如 Color_ 表示 Color_Red、Color_Green、Color_Blue 等?
命名常量是根据它们代表的抽象实体而不是它们引用的数字来命名的吗?
命名约定
约定是否区分本地数据、类数据和全局数据?
该约定是否区分类型名称、命名常量、枚举类型和变量?
该约定是否识别不强制执行的语言中的例程的仅输入参数?
该约定是否尽可能与该语言的标准约定兼容?
名称的格式是否便于阅读?
短名称
代码是否使用长名称(除非有必要使用短名称)?
代码是否避免使用仅保存一个字符的缩写?
所有单词的缩写是否一致?
名字能发音吗?
是否避免了可能读错的名字?
翻译表中是否记录了短名称?
常见命名问题:您是否避免过...
...具有误导性的名称?
...具有相似含义的名称?
...只有一两个字符不同的名称?
...听起来相似的名字?
...使用数字的名称?
...故意拼错名字以使其更短?
...英文中经常拼写错误的名字?
...与标准库例程名称或预定义变量名称冲突的名称?
...完全随意的名字?
...难以阅读的字符?
Read "Code Complete" book, more specifically Chapter 11 about Naming. This is the checklist (from here, free registration required):
General Naming Considerations
Does the name fully and accurately describe what the variable represents?
Does the name refer to the real-world problem rather than to the programming-language solution?
Is the name long enough that you don't have to puzzle it out?
Are computed-value qualifiers, if any, at the end of the name?
Does the name use Count or Index instead of Num?
Naming Specific Kinds Of Data
Are loop index names meaningful (something other than i, j, or k if the loop is more than one or two lines long or is nested)?
Have all "temporary" variables been renamed to something more meaningful?
Are boolean variables named so that their meanings when they're True are clear?
Do enumerated-type names include a prefix or suffix that indicates the category-for example, Color_ for Color_Red, Color_Green, Color_Blue, and so on?
Are named constants named for the abstract entities they represent rather than the numbers they refer to?
Naming Conventions
Does the convention distinguish among local, class, and global data?
Does the convention distinguish among type names, named constants, enumerated types, and variables?
Does the convention identify input-only parameters to routines in languages that don't enforce them?
Is the convention as compatible as possible with standard conventions for the language?
Are names formatted for readability?
Short Names
Does the code use long names (unless it's necessary to use short ones)?
Does the code avoid abbreviations that save only one character?
Are all words abbreviated consistently?
Are the names pronounceable?
Are names that could be mispronounced avoided?
Are short names documented in translation tables?
Common Naming Problems: Have You Avoided...
...names that are misleading?
...names with similar meanings?
...names that are different by only one or two characters?
...names that sound similar?
...names that use numerals?
...names intentionally misspelled to make them shorter?
...names that are commonly misspelled in English?
...names that conflict with standard library-routine names or with predefined variable names?
...totally arbitrary names?
...hard-to-read characters?