180

In the last weeks I've seen some guys using really long names for a Method or Class (50 characters), this is usually under the premise that it improves readability, my opinion is that a long name like this is an indicator that we are trying to do a lot or too much in a method class if we need such a long name, however I wanted to know what do you guys think about it.

An Example is:

getNumberOfSkinCareEligibleItemsWithinTransaction
Sam R.
  • 16,027
  • 12
  • 69
  • 122
MexicanHacker
  • 2,685
  • 3
  • 19
  • 20
  • 20
    YES it's a "code smell"... http://c2.com/cgi/wiki?LongMethodSmell – Dan Rosenstark Feb 09 '10 at 17:00
  • 25
    When it's > 666 characters long then you know you have a problem. – Thomas Eding Feb 09 '10 at 17:01
  • 9
    @yar in your example, the opposite of "Long Method" is "Short Method" which is considered a good thing. So it's obviously not referring to the method name; it's referring to lines of code (or soemthing similar). for example, `f()` is a very short function, but it's certainly not good practice ... and something you should tell some programming mathematicians out there :) – sfussenegger Feb 09 '10 at 17:21
  • 3
    @sfussenegger, it's true. But I'm betting on a correlation between method-name length and method length. `f()` may not be a great function, but that `$()` guy is like a rockstar in the Javascript method world. – Dan Rosenstark Feb 09 '10 at 18:39
  • 7
    @yar, the link you gave referred to the length of the method in lines, not the length of the method _name_. – Thorbjørn Ravn Andersen Feb 09 '10 at 18:40
  • @yar good point :) but those poor guys neither have decent autocompletion nor a compiler that catches (most) typos. To me, the `$()` is like making fire: it's not that impressive if you have the right tools :D – sfussenegger Feb 09 '10 at 23:28
  • @yar f() would be good if you were playing codegolf or coding in golfscript – Tom Neyland Feb 10 '10 at 01:04
  • Well, looking at that I have some idea of what the method is and it sounds like it only does one thing. So it improves readability. Writability, on the other hand, perhaps not. – Duncan Feb 10 '10 at 01:20
  • @Thorbjørn Ravn Andersen I know but man was I fast. But as I said after, I'm betting on a correlation between length of name and length of function. Except where it's an inverse relationship, like "process." – Dan Rosenstark Feb 10 '10 at 02:27
  • 1
    If you have code completion available in your ide, I would rather the name be as long as it needs to be for clarity. That way, when you are presented with a list of methods to call... you can understand them by just scanning the names. – Ryan Ferretti Feb 10 '10 at 15:12
  • @Tnay: Then again, most code golf entries wouldn't pass your average code review. – Aistina Feb 16 '10 at 19:39
  • @Aistina, yeah I imagine the WTFs/min rate would be rather high – Tom Neyland Feb 17 '10 at 18:01
  • If that code deals exclusively with SkinCare products, then you can omit that part of the function name. If not, all SkinCare related functions should be class methods (still alowing you to omit "SkinCare") – Ponkadoodle May 28 '10 at 23:42
  • [This article](http://www.codinghorror.com/blog/archives/000553.html) is a nice read and it's kind of related to your question. – Erethon Feb 10 '10 at 03:08
  • You can shorten your method names however much you want but `InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonPainter.q()` will still be absurd. – nanofarad Jul 24 '13 at 17:44
  • @yar I don't agree with the code smell idea. The link is `old` and it is also talking about `If one is doing procedural-style code` .. – Jonas Geiregat Mar 04 '14 at 15:43
  • @JonasGeiregat yeah, in 2010 that link was actually different ;) – Dan Rosenstark Mar 06 '14 at 02:10
  • I don't think I will ever understand SO. Having seem some nice questions closed because of "opinion based" while they were not, this question still remains open, when the OP specifically asked for "opinions". Why is this the case? – Jorjon Jul 14 '14 at 16:14
  • Can I suggest the name isn't length isn't so important, but rather the amount of verbs and nouns?? – Vishal Sakaria Apr 27 '16 at 09:21

21 Answers21

437

A name in Java, or any other language, is too long when a shorter name exists that equally conveys the behavior of the method.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 327
    So, for example, `boolean doesShorterNameExistThatEquallyConvaysTheBehaviorOfTheMethod(String s)` should be refactored to `boolean isTooLong(String s)`. – Mark Bolusmjak Feb 09 '10 at 17:08
  • 7
    I don't quite agree, as you not only want to convey the behaviour but also keep the project's and language's convention. So in Python you might say `eligible_items_cnt` but in Java you usually say `getEligibleItemsCount`. – flybywire Feb 09 '10 at 17:14
  • 18
    @flybywire: Any convention that makes you write overly long names is of dubious benefit. – MAK Feb 09 '10 at 17:45
  • 4
    @flybywire: The point of convention (as stated by the Ruby on Rails folks) is to reduce the details you have to state explicitly. Conventions are specifically in place to allow you to summarize. – S.Lott Feb 09 '10 at 17:47
  • 22
    @MAK @S.Lott what about `getLength()` vs. `length()`? I really love to look at autocompletions after typing 'get' or 'set' - so I'd prefer convetion over conciseness in this case. – sfussenegger Feb 09 '10 at 17:52
  • ... but to me, this answer only seems appropriate until you start thinking about the problem anyway. – sfussenegger Feb 09 '10 at 17:53
  • 2
    What about abbreviations? They will convey the exact same thing as the non-abbreviated version, but are often harder to read. – Jacob Bellamy Feb 09 '10 at 23:24
  • 3
    @Ricket - And yet also so completely vague as to be useless. – Justin Feb 09 '10 at 23:58
  • 4
    @sfussenegger: Ubiquitous get/set accessors are a common sign that you're breaking encapsulation; for example, you should have length/resize methods instead of getLength/setLength. Tools change through updates and being replaced, and I'm going to choose my names based on something more than the current code completion behavior of one specific editor. (Why can't you just type a period and get a list, anyway? Code completion is a poor substitute even for generated documentation.) –  Feb 10 '10 at 03:08
  • 2
    @flybywire: Good conventions allow you to express deeper, richer, and more nuanced meaning tersely. Thus if the conventions are good, there will be no shorter name that equally conveys behavior. –  Feb 10 '10 at 03:20
  • 1
    @Roger Pate: you may use completion after typing period, true. But using common suffixes makes it easier to inspect certain groups of methods (e.g. setters, getters, anything that starts with write, create, save, count or whatever). Too me, method names are not only about conciseness or descriptiveness, they are about usability and productivity too. Showing methods in alphabetical order isn't specific to just a few tools and is not very likely to become obsolete in near future, is it? Breaking encapsulation is another problem, especially with the POJO hype of recent years. – sfussenegger Feb 10 '10 at 10:32
  • I see where you're getting to mister – Lucian Enache May 30 '14 at 12:57
  • IfYourMethodNameIsSoLongThatItStartsToGivePeopleMigraineHeadachesThenYouShouldReallyConsiderMovingSomeOfThatInformationIntoTheMethodCommentThatsWhatCommentsAreFor – Oliver Watkins Jun 15 '22 at 08:54
212

Some techniques for reducing the length of method names:

  1. 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

  2. You can change within to in, getNumberOfEligibleItemsInTransaction

  3. You can change Transaction to Tx, which gets you to getNumberOfEligibleItemsInTx.

  4. Or if the method accepts a param of type Transaction you can drop the InTx altogether: getNumberOfEligibleItems

  5. You change numberOf by count: getEligibleItemsCount

Now that is very reasonable. And it is 60% shorter.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
flybywire
  • 261,858
  • 191
  • 397
  • 503
  • 11
    additionally, 5) will put `getEligibleItems()` and `getEligibleItemsCount()` next to each other in alphabetically ordered lists (e.g. autocompletion or javadoc) – sfussenegger Feb 09 '10 at 17:37
  • 4
    And as is usually true, the shorter name fits withing the haiku rule. – sal Feb 09 '10 at 18:18
  • 1
    Why not just call it `countEligibleItems`? – mercator Feb 09 '10 at 19:40
  • 2
    @mercator Using a standard convention like getEligibleItems over countEligibleItems reduces the chance for ambiguity in the statement. The less ambiguous as to what the method is supposed to do increases readablity. Without looking further into the method a method that "counts" is less clear than what a method that "gets" accomplishes in the long run. – Bill Feb 09 '10 at 23:09
  • 1
    @Bill I understand what you're saying about ambiguity. I've been confused by code following a "convention" of 3 synonyms for "get" to express 3 slightly different ways of "getting". But some people seem to think the convention is to only use the verbs `get`, `set` or `is`, which is exactly the kind of thing that leads to long names like this. – mercator Feb 11 '10 at 21:43
  • 1
    I know the question is about Java not C# but the Microsoft style guidelines would favour Transaction over Tx. – Joe Feb 12 '10 at 13:05
  • 59
    I dislike abbr like `Tx`, `Cnt`, `grph`, and so on... (btw, `Tx` is short for "Transmission" or "Transmitter") – Meinersbur Feb 14 '10 at 12:38
  • 15
    Yeah, I agreed with you until you decided to use "Tx". – Ponkadoodle May 28 '10 at 23:40
  • 2
    6. `countEligibleItems` 7. `countEligible` 8. `eligible` - since it returns `int` you should guess that it means count ;) 9. `el` – prostynick Jun 17 '11 at 09:15
  • 2
    @Bill: With getEligibleItems I would expect that the method returns a collection of item objects instead of just the count – Tobias Lott Sep 21 '15 at 12:38
  • 1
    "Tx" is what makes code unreadable. You wanted to make your code better and effectively you obfuscated it. – Android developer Apr 15 '17 at 14:40
  • 2
    Eligible items in Texas. – antonagestam Feb 17 '20 at 14:08
194

Just for a change, a non-subjective answer: 65536 characters.

A.java:1: UTF8 representation for string "xxxxxxxxxxxxxxxxxxxx..." is too long for the constant pool

;-)

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 4
    yeah its too long when the JVM cant handle it no mo :) – Anurag Feb 09 '10 at 17:32
  • 40
    +1 for _THE_ literal answer. – sal Feb 09 '10 at 19:47
  • 39
    Technically, the Java language spec doesn't have an upper limit for identifier length. This is a limitation of your JVM implementation. Cheers! – uckelman Feb 09 '10 at 23:45
  • 13
    Sun's compiler apparently doesn't conform to the spec. http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.8 says: "An identifier is an unlimited-length sequence..." – Michael Myers Mar 04 '10 at 22:39
  • 6
    The JVM spec _does_ have an upper limit, as the error message points out. The constant pool representation of utf8's is limited to 2^16 bytes [specified here](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#7963). Class names and method names must be stored as utf8's in the constant pool. – thejoshwolfe Aug 12 '11 at 09:39
  • 1
    [Ah yes, the Engineer's answer. Technically correct, but a bit useless.](http://www.design.caltech.edu/erik/Misc/balloon.html) – Mateen Ulhaq Jul 05 '17 at 11:47
45

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?

  • Because they are not called in other code.
  • Because they are used as test names.
  • Because they then can be written as sentences describing requirements. (For example, using AgileDox)

Example:

    @Test
    public void testDialogClosesDownWhenTheRedButtonIsPressedTwice() {
        ...
    }

See "Behavior Driven Design" for more info on this idea.

Epaga
  • 38,231
  • 58
  • 157
  • 245
  • 5
    +1 I agree with it and it's also what I'm doing, although JUnit 4 methods are not required to start with `test` anymore, this opens also the possibility to use `should`: such as `dialogShouldCloseWhenTheRedButtonIsPressedTwice()`. Or you can call the test class `DialogShould` and then the method `closeWhenTheRedButtonIsPressedTwice()`, so to read them together: `DialogShould.closeWhenTheRedButtonIsPressedTwice()`. – stivlo Nov 13 '11 at 02:24
  • 3
    Whilst I agree, I'd also suggest that too long a sentence *may* suggest a test that is doing too much! – Brian Agnew Dec 19 '17 at 12:30
  • 1
    Alternatively, one could use the annotation `@DisplayName` if the name of the method is too long. For example: `@DisplayName("Dialog closes down when the red button is pressed twice")` – Navigatron Aug 31 '22 at 14:26
17

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.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
13

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.

flybywire
  • 261,858
  • 191
  • 397
  • 503
12

I tend use the haiku rule for names:

 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.

sal
  • 23,373
  • 15
  • 66
  • 85
12

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.

Jay
  • 26,876
  • 10
  • 61
  • 112
11

Design your interface the way you want it to be, and make the implementation match.

For example, maybe i'd write that as

getTransaction().getItems(SKIN_CARE).getEligible().size()

or with Java 8 streams:

getTransaction().getItems().stream()
    .filter(item -> item.getType() == SKIN_CARE)
    .filter(item -> item.isEligible())
    .count();
Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
6

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.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • I like rules like this. As long as you keep in mind that you/your team made them up randomly, it's all good. On the other hand, I can't upvote this because "research showing" would actually need a link to that research, or something about it... – Dan Rosenstark Feb 11 '10 at 19:33
5

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
4

When you are going to write a method name next time , just think the bellow quote

"The man who is going to maintain your code is a phyco who knows where you stay"
2

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()"

Jesse
  • 346
  • 4
  • 10
2

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.

Ben Gartner
  • 14,413
  • 10
  • 36
  • 34
1

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.

vdboor
  • 21,914
  • 12
  • 83
  • 96
  • You could always argue the other way around. When it is verbosively explains what the thing is about it is obviously clear what the method does else it might cause confusion and might provoke wrong use of the method. – Jonas Geiregat Mar 04 '14 at 15:47
1

As with any other language: when it no longer describes the single action the function performs.

Kaz Dragon
  • 6,681
  • 2
  • 36
  • 45
1

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.

Bill K
  • 62,186
  • 18
  • 105
  • 157
1

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.

Brian T Hannan
  • 3,925
  • 18
  • 56
  • 96
0

An identifier name is too long when it exceeds the length your Java compiler can handle.

uckelman
  • 25,298
  • 8
  • 64
  • 82
  • 3
    What?! I don't see why I was downvoted for this. The question didn't ask for a necessary condition, just a sufficient one! – uckelman Feb 09 '10 at 23:44
0

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 :)

HackerGil
  • 1,562
  • 2
  • 11
  • 12
0

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)

Paul Gregoire
  • 9,715
  • 11
  • 67
  • 131