I try to be rather descriptive with my function names, where possible. This occasionally results in function names in the twenty to thirty character range such as "GetActionFromTypeName" or "GetSelectedActionType". At what point do functions get too long to manage (not too long for the compiler)?
As long as the functions actually do what their name suggest they do and you're not going for a code golf entry, I think it's a good thing.
When you can't read them aloud anymore without taking a breath in the middle =D
In my opinion a function name should be exactly as long as needed to describe what its purpose is. If you think that the name of the function is too long, then that may be an indication of that it tries to do too many things, and should be refactored.
I don't think a method name can be too long as long as it is descriptive. If a method name goes over 40 characters I will see if I can convey the same meaning in fewer words. If not I'll live with the long name in for the sake of clarity.
I'd say when you find yourself finding abbreviations for their names when referring to them. I also find it too much when people start describing pre-/post-/parameter- conditions in the names or giving hints on the implementation. (like getVersionInformationFormTheDatabase()
or doSomethingWithoutCheckingFooFirst()
)
If there's a shorter, but yet descriptive way to name the function, then the function name is too long.
TheFunctionNameBecomesTooLongWhenItBecomesTooHardToReadItAndUnderstandIt, on the other hand it_dependends_on_nameing_convention_how_hard_function_reading_is_sometimes_long_names_are_readable.
IMHO, it is much more important for functions to be descriptive. IDEs help much avoiding the trouble of mispelling or something like that. I think its ok to use abbreviations sometimes, as long as they are consistent through the code (no different abbreviations for the same thing, nor same abbreviation for two different things.
A function name is too long when it starts to either over-describe what it does, or when it hinders readability of the code.
I think that this is especially important for public names - they should not be too long, but how long too long is is very subjective. Always have better a longer and descriptive name than a too short name.
For private methods even very long names are really no problem in my opinion.
If the function name is 'too long' then it is likely that the function itself is also too long and has too much responsibility. Many wise programmers say that a function should do one thing and one thing only. A function whose name that has to be long to accurately describe what it does is likely to be a good candidate for refactoring into multiple smaller and simpler private functions that consequently have shorter names.
Trying to avoid subjectivity:
When names get to be about 1/3 of whatever your typical line length is, then you're stretching it. At 1/2 line length you're too far gone. One statement per line gets pretty tough when the names take up the whole line.
Beyond that, most IDEs support completion (thereby saving the programmer from actually typing most names out fully), so the more important thing to do, in my opinion, is make sure that the name is as unique as possible as soon as possible.
I think you should worry more about when a function name is too short, or not descriptive enough. As long as your function does what its name describes (and everything its name describes), it is well-named. I often write functions with long names like getPropertyNameArrayFromObject (though I tend to underscore rather than camelize), which could be called getObjPropArr or something else but wouldn't be as descriptive. I tend to stay away from abbreviations because they become ambiguous when you go work on something else and come back to the code.
On the other hand, consider many built in PHP functions such as stricmp which should really be named something along the lines of caseInsensitiveStringComparison.
And there are cases where I intentionally write very short function names that are not descriptive at all. Sometimes I just want a short JavaScript function to act as a shortcut. For example, I generally alias $(id) to document.getElementById(id) because I get sick of typing that out.
Method names can be very very long depending on the language (Maximum Method Name Length). At some point your going to use that function or method and typing out a sentence for a function names seems unnecessary.
Keep your code maintainable, use comments instead.
If a compiler has some limitations on variable names, it's often 64 or 128 characters or somewhere in-between. In the past, 32 characters have also been popular. If they do have a limit, they often just take the first n characters and ignore the rest.
General rule is that the function name provides a very short description of what it's doing. Most of such descriptions should easily fit within 32 characters. (Use CamelCase to separate words.) Since most IDE's now provide Code Completion, making errors with function names does tend to be rare. But do make it yourself easier by making sure most functions differ from each other with the first 8 characters. Something like DateCalculationAddMonth, DateCalculationAddWeek, DateCalculationAddYear and DateCalculationAddDay should be avoided. Use AddMonthDateCalculation, AddWeekDateCalculation, AddYearDateCalculation and AddDayDateCalculation. (Btw, these are silly examples but I hope you understand my drift.)
Actually, it might be better to add (group) your functions to a separate class. With above silly example, you could just create a class DateCalculation and add four (static/class) functions (AddMonth, AddWeek, AddYear and AddDay) to that class. Basically, this would be more useful when you have many similar functions which would all have very long names if you don't group them together in separate classes.
- If you have to scroll to the right to read it.
- Describes the 3 or more things that is does - it shouldn't do that many things.
- Your boss thinks its too long.
- It's longer than the code itself.
- It starts with Get, just like 500 other functions.
- Nobody wants to use it.
- There is another function that does the same thing with a shorter name that users understand.
- It can be made shorter.
Ah, a question with no answer!
I tend to find if I can't encapsulate it in a few words, then there's something up with the design (paracribbing from Code Complete).
So while I'm happy with FindArticlesWithoutTitles
I would probably be disgusted by FindArticlesWithoutTitlesThenApplyDefaultStyles
. This is just wrong; either the name is too technical and not describing it's actual function (titles without articles often need styles to be fixed, so this would be FixArticleStyles
) or it should be two functions: FindArticlesWithoutTitles/ApplyDefaultStyles
.
Also: frequency has much to do with it. If it's used often, I want it to be short, to reduce the glare of the code; long repetitive names make code ugly to read and a pain to type. If I'm always finding FindArticlesWithoutTitles
I might just shorten to FindNoTitles
depending on the appropriate context or maybe even just FindArticles
if I have no other article finding functions.
It may be a bit off topic, but as you asked specifically for a function name guideline (as opposed to say, method), I figured I would quote Linus Torvalds on naming (although it more refers to variables, but still - the principles hold).
Chapter 3: Naming
C is a Spartan language, and so should your naming be. Unlike Modula-2 and Pascal programmers, C programmers do not use cute names like ThisVariableIsATemporaryCounter. A C programmer would call that variable "tmp", which is much easier to write, and not the least more difficult to understand.
Short, descriptive names go well with short, specific functions... which go well with code reuse.
When it contains information which is obvious from context (e.g., incrementInteger(int x), long longID), useless (e.g., ObsoleteIncrementer, RobertsCarFactory), incomprehensible (e.g., TheFunctionThatRobertWorkedOnLastWeekButDidntFinish), numeric (e.g., id1, id2, id3) or otherwise doesn't help understanding or contains a code smell. Note that even though some part of the names above should be pruned, you might need to pad them with useful information to keep them unique and make them understandable, as in person_id for id1, employer_id for id2 etc..
The function name is too long when it would save you work to use a shorter one.
The reason we usually go for descriptive function names is because it saves us work. (by making it easier to understand and maintain the code). So it logically follows that you should not give your functions names that are so long that it costs you extra time (making the code harder to read, for example)
From Code Complete (1st Edition, page 188)
"Gorla, Benander and Benander found that the effort required to debug a COBOL program was minimized when variables had names that averaged 10 to 16 characters (1990). Programs with names averaging 8 to 20 characters were almost as easy to debug."
This constitutes the only empirical discussion of a reasonable guideline for variable name length I've ever seen. Everything else is down to opinion and comfort.
IMO, it's too long when it has a conjunction in it. "When", "And", "Then", ... anything like that. Following the One Responsibility Rule should allow function names that are long enough to be descriptive and short enough not to be ridiculously annoying.
Ask yourself a more interesting question: Why do we make function names long? It's in order to describe what the function does. Well, I submit this hypothesis:
The amount of description necessary in a function name is inversely proportional to the amount of type information available for it.
To illustrate the point, if you saw a function like this...
public <A> A id(A a);
...what would you think it does? The type information tells you everything you need to know. Barring side-effects and exceptions, there is only one thing that this function could possibly do.
Of course, you are probably working in a language that allows unfettered side-effects, so that function could, say, write to a file. But if it does then its type is a lie. Working in a language that declares effects in types allows you to use very terse names without any loss of descriptiveness.
Sometimes the 30-character limit in many contexts in Oracle SQL and PL/SQL felt like a terrible restriction, but on reflection it has caused us many times to think hard about how to name things so that they are quickly understood by someone reading the code later.
If we couldn't adequately describe the purpose of a table, view, function, procedure, package, etc. using 30 characters without using excessive abbreviation, it just needed a bit more thought, and perhaps an additional layer of abstraction to group related things together.
Function and method names start getting too long when the developer forgets about the descriptive nature of arguments (assuming meaningful argument and variable names). For example:
my $template = HTML::Template->new( filename => 'home.html');
$template->param( title => 'Home Page' );
$html = $template->output;
is transparent in what it does even if you know no Perl and have never heard of HTML::Template.
I have seen too often the temptation to name that output
method something like RenderHTMLViewFromTemplateObject
. If all the libraries used have such naming conventions, it becomes simply impossible for me to follow what is going on.
While extracting methods during refactoring I sometimes have difficulty choosing a name when conditional logic is introduced. For example, what descriptive name would be suitable for function x (a pseudo-sample method of a ManagedBean in a JSF application I'm writing)
public class myUser() {
private String userId;
private MigrationService service;
...
public String function x() {
boolean isMigrated = service.isMigrated(userId);
if (isMigrated) {
outcome = retrieveData(); // a private method not shown here
} else {
outcome = "not migrated";
}
}
}
Some possibilities I thought of include:
checkMigrationStatusAndIfMigratedRetrieveData
checkMigrationStatus
retrieveDataIfMigrated
How do you handle conditions in descriptive function names? It's problematic because if the conditions change, your function name changes if you include that level of detail. If you leave it out, the method may be doing more than the name states. What to do?
Thanks!