A variable name is too long when a shorter name will allow for better code readability over the entire program, or the important parts of the program.
If a longer name allows you to convey more information about a value. However, if a name is too long, it will clutter the code and reduce the ability to comprehend the rest of the code. This typically happens by causing line wraps and pushing other lines of code off the page.
The trick is determining which will offer better readability. If the variable is used often or several times in a short amount of space, it may be better to give it a short name and use a comment clarify. The reader can refer back to the comment easily. If the variable is used often throughout the program, often as a parameter or in other complicated operations, it may be best to trim down the name, or use acronyms as a reminder to the reader. They can always reference a comment by the variable declaration if they forget the meaning.
This is not an easy trade off to make, since you have to consider what the code reader is likely to be trying to comprehend, and also take into account how the code will change and grow over time. That's why naming things is hard.
Readability is why it's acceptable to use i as a loop counter instead of DescriptiveLoopCounterName. Because this is the most common use for a variable, you can spend the least amount of screen space explaining why it exists. The longer name is just going to waste time by making it harder to understand how you are testing the loop condition or indexing into an array.
On the other end of the spectrum, if a function or variable is used rarely as in a complex operation, such as being passed to a multi-parameter function call, you can afford to give it an overly descriptive name.
It's too long when the name of the method wraps onto another line and the call to the method is the only thing on the line and starts pretty close to the margin. You have to take into account the average size of the screen of the people who will be using it.
But! If the name seems too long then it probably is too long. The way to get around it is to write your code in such a way that you are within a context and the name is short but duplicated in other contexts. This is like when you can say "she" or "he" in English instead of someone's full name.
There are two ways or points of view here: One is that it really doesn't matter how long the method name is, as long as it's as descriptive as possible to describe what the method is doing (Java best practices basic rule). On the other hand, I agree with the flybywire post. We should use our intelligence to try to reduce as much as possible the method name, but without reducing it's descriptiveness. Descriptiveness is more important :)
老实说,名称只需要传达信息其目的是让开发人员将其用作公共 API 方法,或者在您离开时必须维护代码。只要记住 KISS(保持简单愚蠢)
A name is too long if it:
Takes more than 1 second to read
Takes up more RAM than you allocate for your JVM
Is something absurdly named
If a shorter name makes perfect sense
If it wraps around in your IDE
Honestly the name only needs to convey its purpose to the the Developers that will utilize it as a public API method or have to maintain the code when you leave. Just remember KISS (keep it simple stupid)
Some techniques for reducing the length of method names:
If your whole program, or class, or module is about 'skin care items' you can drop skin care. For example, if your class is called SkinCareUtils, that brings you to getNumberOfEligibleItemsWithinTransaction
You can change within to in, getNumberOfEligibleItemsInTransaction
You can change Transaction to Tx, which gets you to getNumberOfEligibleItemsInTx.
Or if the method accepts a param of type Transaction you can drop the InTx altogether: getNumberOfEligibleItems
You change numberOf by count: getEligibleItemsCount
Now that is very reasonable. And it is 60% shorter.
Context "...WithinTransaction" should be obvious. That's what object-orientation is all about.
The method is part of a class. If the class doesn't mean "Transaction" -- and if it doesn't save you from having to say "WithinTransaction" all the time, then you've got problems.
Java has a culture of encouraging long names, perhaps because the IDEs come with good autocompletion.
This site says that the longest class name in the JRE is InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState which is 92 chars long.
As for longest method name I have found this one supportsDataDefinitionAndDataManipulationTransactions, which is 52 characters.
Never use a long word when a diminutive one will do.
I don't think your thesis of "length of method name is proportional to length of method" really holds water.
Take the example you give: "getNumberOfSkinCareEligibleItemsWithinTransaction". That sounds to me like it does just one thing: it counts the number of items in a transaction that fall into a certain category. Of course I can't judge without seeing the actual code for the method, but that sounds like a good method to me.
On the other hand, I've seen lots of methods with very short and concise names that do way to much work, like "processSale" or the ever popular "doStuff".
I think it would be tough to give a hard-and-fast rule about method name length, but the goal should be: long enough to convey what the function does, short enough to be readable. In this example, I'd think "getSkinCareCount" would probably have been sufficient. The question is what you need to distinguish. If you have one function that counts skin-care-eligible items in transactions and another that counts skin-care-eligible items in something else, then "withinTransactions" adds value. But if it doesn't mean anything to talk about such items outside of a transaction, then there's no point cluttering up the name with such superfluous information.
Two, I think it's wildly unrealistic to suppose that a name of any manageable length will tell you exactly what the function does in all but the most trivial cases. A realistic goal is to make a name that gives a reader a clue, and that can be remembered later. Like, if I'm trying to find the code that calculates how much antimatter we need to consume to reach warp speed, if I look at function names and see "calibrateTransporter", "firePhasers", and "calcAntimatterBurn", it's pretty clear that the first two aren't it but the third one might be. If I check and find that that is indeed the one I'm looking for, it will be easy to remember that when I come back tomorrow to work on this problem some more. That's good enough.
Three, long names that are similar are more confusing than short names. If I have two functions called "calcSalesmanPay" and "calcGeekPay", I can make a good guess which is which at a quick glance. But if they are called "calculateMonthlyCheckAmountForSalesmanForExportToAccountingSystemAndReconciliation" and "calculateMonthlyCheckAmountForProgrammersForExportToAccountingSystemAndReconciliation", I have to study the names to see which is which. The extra information in the name is probably counter-productive in such cases. It turns a half-second think into a 30-second think.
Seven syllable class names
five for variables
seven for method and other names
These are rules of thumb for max names. I violate this only when it improves readability. Something like recalculateMortgageInterest(currentRate, quoteSet...) is better than recalculateMortgageInterestRate or recalculateMortgageInterestRateFromSet since the fact that it involves rates and a set of quotes should be pretty clear from the embedded docs like javadoc or the .NET equivalent.
NOTE: Not a real haiku, as it is 7-5-7 rather than 5-7-5. But I still prefer calling it haiku.
My rule is as follows: if a name is so long that it has to appear on a line of its own, then it is too long. (In practice, this means I'm rarely above 20 characters.)
This is based upon research showing that the number of visible vertical lines of code positively correlates with coding speed/effectiveness. If class/method names start significantly hurting that, they're too long.
Add a comment where the method/class is declared and let the IDE take you there if you want a long description of what it's for.
The length of the method itself is probably a better indicator of whether it's doing too much, and even that only gives you a rough idea. You should strive for conciseness, but descriptiveness is more important. If you can't convey the same meaning in a shorter name, then the name itself is probably okay.
That method name is definitely too long. My mind tends to wander when I am reading such sized method names. It's like reading a sentence without spaces.
Personally, I prefer as few words in methods as possible. You are helped if the package and class name can convey meaning. If the responsibility of the class is very concise, there is no need for a giant method name. I'm curious why "WithinTransaction" on there.
"getNumberOfSkinCareEligibleItemsWithinTransaction" could become:
发布评论
评论(21)
当较短的名称可以使整个程序或程序的重要部分的代码具有更好的可读性时,变量名称太长。
如果较长的名称允许您传达有关值的更多信息。但是,如果名称太长,就会使代码变得混乱并降低理解其余代码的能力。这通常是通过导致换行并将其他代码行推出页面而发生的。
诀窍是确定哪个将提供更好的可读性。如果该变量在很短的空间内经常或多次使用,最好给它一个简短的名称并使用注释进行澄清。读者可以轻松地回顾评论。如果该变量在整个程序中经常使用,通常作为参数或在其他复杂的操作中使用,那么最好精简名称,或使用缩写词来提醒读者。如果他们忘记了含义,他们总是可以通过变量声明引用注释。
这不是一个容易做出的权衡,因为您必须考虑代码阅读器可能试图理解的内容,并且还要考虑代码将如何随着时间的推移而变化和增长。这就是为什么命名事物很困难。
可读性是为什么使用 i 作为循环计数器而不是 DescriptiveLoopCounterName 是可以接受的。因为这是变量最常见的用途,所以您可以花费最少的屏幕空间来解释它存在的原因。较长的名称只会浪费时间,让您更难理解如何测试循环条件或索引到数组中。
另一方面,如果函数或变量在复杂操作中很少使用,例如传递给多参数函数调用,则可以给它一个过于描述性的名称。
A variable name is too long when a shorter name will allow for better code readability over the entire program, or the important parts of the program.
If a longer name allows you to convey more information about a value. However, if a name is too long, it will clutter the code and reduce the ability to comprehend the rest of the code. This typically happens by causing line wraps and pushing other lines of code off the page.
The trick is determining which will offer better readability. If the variable is used often or several times in a short amount of space, it may be better to give it a short name and use a comment clarify. The reader can refer back to the comment easily. If the variable is used often throughout the program, often as a parameter or in other complicated operations, it may be best to trim down the name, or use acronyms as a reminder to the reader. They can always reference a comment by the variable declaration if they forget the meaning.
This is not an easy trade off to make, since you have to consider what the code reader is likely to be trying to comprehend, and also take into account how the code will change and grow over time. That's why naming things is hard.
Readability is why it's acceptable to use i as a loop counter instead of DescriptiveLoopCounterName. Because this is the most common use for a variable, you can spend the least amount of screen space explaining why it exists. The longer name is just going to waste time by making it harder to understand how you are testing the loop condition or indexing into an array.
On the other end of the spectrum, if a function or variable is used rarely as in a complex operation, such as being passed to a multi-parameter function call, you can afford to give it an overly descriptive name.
与任何其他语言一样:当它不再描述函数执行的单个操作时。
As with any other language: when it no longer describes the single action the function performs.
我想说的是,结合使用好的答案并且保持合理。
完整、清晰、易读地描述该方法的作用。
如果方法名称看起来太长,请重构该方法以减少其执行的操作。
I'd say use a combination of the good answers and be reasonable.
Completely, clearly and readably describe what the method does.
If the method name seems too long--refactor the method to do less.
当方法的名称换行到另一行并且对方法的调用是该行上唯一的内容并且从非常接近边缘的位置开始时,就太长了。您必须考虑使用它的人的屏幕平均尺寸。
但!如果名称看起来太长,那么它可能太长了。解决这个问题的方法是以这样的方式编写代码:您位于一个上下文中,并且名称很短但在其他上下文中重复。这就像你可以用英语说“她”或“他”而不是某人的全名。
It's too long when the name of the method wraps onto another line and the call to the method is the only thing on the line and starts pretty close to the margin. You have to take into account the average size of the screen of the people who will be using it.
But! If the name seems too long then it probably is too long. The way to get around it is to write your code in such a way that you are within a context and the name is short but duplicated in other contexts. This is like when you can say "she" or "he" in English instead of someone's full name.
当它过于冗长地解释事情的内容时就太长了。
例如,这些名称在功能上是等效的。
在 Java 中:
java.sql.SQLIntegrityConstraintViolationException
在 Python/Django 中:
django.db.IntegrityError
问问自己,在 SQL/db 包中,还有多少种类型的完整性错误你想出什么办法吗? ;)
因此 db.IntegrityError 就足够了。
It's too long when it too verbosively explains what the thing is about.
For example, these names are functionally equivalent.
in Java:
java.sql.SQLIntegrityConstraintViolationException
in Python/Django:
django.db.IntegrityError
Ask yourself, in a SQL/db package, how many more types of integrity errors can you come up with? ;)
Hence
db.IntegrityError
is sufficient.当标识符名称超过 Java 编译器可以处理的长度时,它就太长了。
An identifier name is too long when it exceeds the length your Java compiler can handle.
这里有两种方法或观点:一种是方法名有多长其实并不重要,只要它尽可能描述性地描述方法正在做什么(Java 最佳实践基本规则)。另一方面,我同意飞线帖子。我们应该利用我们的智慧来尝试尽可能减少方法名称,但不降低其描述性。描述性更重要:)
There are two ways or points of view here: One is that it really doesn't matter how long the method name is, as long as it's as descriptive as possible to describe what the method is doing (Java best practices basic rule). On the other hand, I agree with the flybywire post. We should use our intelligence to try to reduce as much as possible the method name, but without reducing it's descriptiveness. Descriptiveness is more important :)
如果出现以下情况,则名称太长:
老实说,名称只需要传达信息其目的是让开发人员将其用作公共 API 方法,或者在您离开时必须维护代码。只要记住 KISS(保持简单愚蠢)
A name is too long if it:
Honestly the name only needs to convey its purpose to the the Developers that will utilize it as a public API method or have to maintain the code when you leave. Just remember KISS (keep it simple stupid)
当存在同样表达方法行为的较短名称时,Java 或任何其他语言中的名称就太长。
A name in Java, or any other language, is too long when a shorter name exists that equally conveys the behavior of the method.
减少方法名称长度的一些技巧:
如果您的整个程序、类或模块都是关于“皮肤护理项目”的,您可以放弃皮肤护理。例如,如果您的类名为
SkinCareUtils
,这会将您带到
getNumberOfEligibleItemsWithinTransaction
您可以将 within 更改为 in,
getNumberOfEligibleItemsInTransaction
您可以将Transaction更改为Tx,这样您就可以
getNumberOfEligibleItemsInTx
。或者,如果该方法接受
Transaction
类型的参数,您可以完全删除 InTx:getNumberOfEligibleItems
您按计数更改 numberOf:
getEligibleItemsCount
现在这是非常合理的。而且缩短了 60%。
Some techniques for reducing the length of method names:
If your whole program, or class, or module is about 'skin care items' you can drop skin care. For example, if your class is called
SkinCareUtils
,that brings you to
getNumberOfEligibleItemsWithinTransaction
You can change within to in,
getNumberOfEligibleItemsInTransaction
You can change Transaction to Tx, which gets you to
getNumberOfEligibleItemsInTx
.Or if the method accepts a param of type
Transaction
you can drop the InTx altogether:getNumberOfEligibleItems
You change numberOf by count:
getEligibleItemsCount
Now that is very reasonable. And it is 60% shorter.
只是为了改变,一个非主观的答案:65536 个字符。
;-)
Just for a change, a non-subjective answer: 65536 characters.
;-)
我同意大家的观点:方法名不宜太长。不过,我确实想添加一个例外:
但是,JUnit 测试方法的名称可以很长并且应该类似于句子。
为什么?
示例:
请参阅“行为驱动设计" 了解有关此想法的更多信息。
I agree with everyone: method names should not be too long. I do want to add one exception though:
The names of JUnit test methods, however, can be long and should resemble sentences.
Why?
Example:
See "Behavior Driven Design" for more info on this idea.
上下文“...WithinTransaction”应该是显而易见的。这就是面向对象的全部内容。
该方法是类的一部分。如果该类的意思不是“Transaction”——并且如果它不能让您不必一直说“WithinTransaction”,那么您就会遇到问题。
Context "...WithinTransaction" should be obvious. That's what object-orientation is all about.
The method is part of a class. If the class doesn't mean "Transaction" -- and if it doesn't save you from having to say "WithinTransaction" all the time, then you've got problems.
Java 有一种鼓励使用长名称的文化,也许是因为 IDE 具有良好的自动完成功能。
此站点表示 JRE 中最长的类名称是
InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState 长度为 92 个字符。
至于最长的方法名称,我找到了这个
supportsDataDefinitionAndDataManipulationTransactions
,它有52个字符。Java has a culture of encouraging long names, perhaps because the IDEs come with good autocompletion.
This site says that the longest class name in the JRE is
InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState
which is 92 chars long.As for longest method name I have found this one
supportsDataDefinitionAndDataManipulationTransactions
, which is 52 characters.当可以使用短词时,永远不要使用长词。
我认为你的“方法名称的长度与方法的长度成正比”的论点真的站不住脚。
以您给出的示例为例:“getNumberOfSkinCareEligibleItemsWithinTransaction”。在我看来,它只做了一件事:它计算交易中属于特定类别的项目数量。当然,如果没有看到该方法的实际代码,我无法做出判断,但这对我来说听起来是一个很好的方法。
另一方面,我见过许多名称非常简短的方法,它们可以完成很多工作,例如“processSale”或曾经流行的“doStuff”。
我认为很难给出关于方法名称长度的硬性规则,但目标应该是:足够长以传达函数的功能,足够短以易于阅读。在这个例子中,我认为“getSkinCareCount”可能就足够了。问题是你需要区分什么。如果您有一个函数对交易中符合护肤资格的商品进行计数,而另一个函数则对其他交易中符合护肤资格的商品进行计数,那么“withinTransactions”会增加价值。但如果在交易之外谈论这些项目没有任何意义,那么就没有必要用这些多余的信息来混淆名称。
第二,我认为假设任何可管理长度的名称都能准确地告诉您该函数在除了最琐碎的情况之外的所有情况下的作用是非常不现实的。一个现实的目标是起一个能给读者提供线索并且以后可以记住的名字。就像,如果我试图找到计算我们需要消耗多少反物质才能达到扭曲速度的代码,如果我查看函数名称并看到“calibrateTransporter”、“firePhasers”和“calcAntimatterBurn”,很明显前两个不是,但第三个可能是。如果我检查并发现这确实是我正在寻找的问题,那么当我明天回来进一步解决这个问题时,就会很容易记住这一点。这就足够了。
三、相似的长名字比短名字更容易混淆。如果我有两个名为“calcSalesmanPay”和“calcGeekPay”的函数,我可以一眼就猜出哪个是哪个。但是,如果它们被称为“calculateMonthlyCheckAmountForSalesmanForExportToAccountingSystemAndReconciliation”和“calculateMonthlyCheckAmountForProgrammersForExportToAccountingSystemAndReconciliation”,我必须研究名称以了解哪个是哪个。在这种情况下,名称中的额外信息可能会适得其反。它将半秒的思考变成了 30 秒的思考。
Never use a long word when a diminutive one will do.
I don't think your thesis of "length of method name is proportional to length of method" really holds water.
Take the example you give: "getNumberOfSkinCareEligibleItemsWithinTransaction". That sounds to me like it does just one thing: it counts the number of items in a transaction that fall into a certain category. Of course I can't judge without seeing the actual code for the method, but that sounds like a good method to me.
On the other hand, I've seen lots of methods with very short and concise names that do way to much work, like "processSale" or the ever popular "doStuff".
I think it would be tough to give a hard-and-fast rule about method name length, but the goal should be: long enough to convey what the function does, short enough to be readable. In this example, I'd think "getSkinCareCount" would probably have been sufficient. The question is what you need to distinguish. If you have one function that counts skin-care-eligible items in transactions and another that counts skin-care-eligible items in something else, then "withinTransactions" adds value. But if it doesn't mean anything to talk about such items outside of a transaction, then there's no point cluttering up the name with such superfluous information.
Two, I think it's wildly unrealistic to suppose that a name of any manageable length will tell you exactly what the function does in all but the most trivial cases. A realistic goal is to make a name that gives a reader a clue, and that can be remembered later. Like, if I'm trying to find the code that calculates how much antimatter we need to consume to reach warp speed, if I look at function names and see "calibrateTransporter", "firePhasers", and "calcAntimatterBurn", it's pretty clear that the first two aren't it but the third one might be. If I check and find that that is indeed the one I'm looking for, it will be easy to remember that when I come back tomorrow to work on this problem some more. That's good enough.
Three, long names that are similar are more confusing than short names. If I have two functions called "calcSalesmanPay" and "calcGeekPay", I can make a good guess which is which at a quick glance. But if they are called "calculateMonthlyCheckAmountForSalesmanForExportToAccountingSystemAndReconciliation" and "calculateMonthlyCheckAmountForProgrammersForExportToAccountingSystemAndReconciliation", I have to study the names to see which is which. The extra information in the name is probably counter-productive in such cases. It turns a half-second think into a 30-second think.
我倾向于使用俳句规则来命名:
这些是最大名称的经验规则。仅当它提高可读性时我才违反这一点。像 recalculateMortgageInterest(currentRate, quoteSet...) 这样的东西比 recalculateMortgageInterestRate 或 recalculateMortgageInterestRateFromSet 更好,因为它涉及费率和一组报价的事实应该从 javadoc 或 .NET 等价物等嵌入式文档中非常清楚。
注意:不是真正的俳句,因为它是 7-5-7 而不是 5-7-5。但我还是更喜欢称其为俳句。
I tend use the haiku rule for names:
These are rules of thumb for max names. I violate this only when it improves readability. Something like recalculateMortgageInterest(currentRate, quoteSet...) is better than recalculateMortgageInterestRate or recalculateMortgageInterestRateFromSet since the fact that it involves rates and a set of quotes should be pretty clear from the embedded docs like javadoc or the .NET equivalent.
NOTE: Not a real haiku, as it is 7-5-7 rather than 5-7-5. But I still prefer calling it haiku.
按照您想要的方式设计您的界面,并使实现相匹配。
例如,也许我会将其写为
Java 8 流或与 Java 8 流一起编写:
Design your interface the way you want it to be, and make the implementation match.
For example, maybe i'd write that as
or with Java 8 streams:
我的规则如下:如果一个名称太长以至于必须单独出现在一行中,那么它就太长了。 (实际上,这意味着我很少会超过 20 个字符。)
这是基于研究表明,代码的可见垂直行数与编码速度/有效性呈正相关。如果类/方法名称开始严重损害这一点,那么它们就太长了。
如果您想要详细说明其用途,请在声明方法/类的位置添加注释,然后让 IDE 带您到那里。
My rule is as follows: if a name is so long that it has to appear on a line of its own, then it is too long. (In practice, this means I'm rarely above 20 characters.)
This is based upon research showing that the number of visible vertical lines of code positively correlates with coding speed/effectiveness. If class/method names start significantly hurting that, they're too long.
Add a comment where the method/class is declared and let the IDE take you there if you want a long description of what it's for.
方法本身的长度可能可以更好地指示它是否做了太多事情,即使这样也只能给您一个粗略的想法。你应该力求简洁,但描述性更重要。如果您无法用较短的名称传达相同的含义,那么名称本身可能还可以。
The length of the method itself is probably a better indicator of whether it's doing too much, and even that only gives you a rough idea. You should strive for conciseness, but descriptiveness is more important. If you can't convey the same meaning in a shorter name, then the name itself is probably okay.
当您下次要编写方法名称时,请考虑下面的引用
When you are going to write a method name next time , just think the bellow quote
该方法名称肯定太长了。当我阅读如此大的方法名称时,我的思绪往往会走神。这就像阅读一个没有空格的句子。
就我个人而言,我更喜欢方法中尽可能少的文字。如果包名和类名能够传达含义,就会对您有所帮助。 如果类的职责非常简洁,则不需要巨大的方法名称。我很好奇为什么“WithinTransaction”在那里。
“getNumberOfSkinCareEligibleItemsWithinTransaction”可能会变成:
com.mycompany.app.product.SkinCareQuery.getNumEligibleItems();
然后在使用时,该方法可能看起来像“query.getNumEligibleItems()”
That method name is definitely too long. My mind tends to wander when I am reading such sized method names. It's like reading a sentence without spaces.
Personally, I prefer as few words in methods as possible. You are helped if the package and class name can convey meaning. If the responsibility of the class is very concise, there is no need for a giant method name. I'm curious why "WithinTransaction" on there.
"getNumberOfSkinCareEligibleItemsWithinTransaction" could become:
com.mycompany.app.product.SkinCareQuery.getNumEligibleItems();
Then when in use, the method could look like "query.getNumEligibleItems()"