When is a Java method name too long?

JavaMethods

Java Problem Overview


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

Java Solutions


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

Solution 2 - Java

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.

Solution 3 - Java

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

;-)

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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.

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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"

Solution 13 - Java

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

Solution 14 - Java

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.

Solution 15 - Java

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

Solution 16 - Java

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.

Solution 17 - Java

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.

Solution 18 - Java

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.

Solution 19 - Java

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

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

Solution 21 - Java

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMexicanHackerView Question on Stackoverflow
Solution 1 - JavaJaredParView Answer on Stackoverflow
Solution 2 - JavaflybywireView Answer on Stackoverflow
Solution 3 - JavaMark ByersView Answer on Stackoverflow
Solution 4 - JavaEpagaView Answer on Stackoverflow
Solution 5 - JavaS.LottView Answer on Stackoverflow
Solution 6 - JavaflybywireView Answer on Stackoverflow
Solution 7 - JavasalView Answer on Stackoverflow
Solution 8 - JavaJayView Answer on Stackoverflow
Solution 9 - JavaChristoffer HammarströmView Answer on Stackoverflow
Solution 10 - JavaRex KerrView Answer on Stackoverflow
Solution 11 - JavaBill the LizardView Answer on Stackoverflow
Solution 12 - JavaPassionatedDeveloperView Answer on Stackoverflow
Solution 13 - JavaJesseView Answer on Stackoverflow
Solution 14 - JavaBen GartnerView Answer on Stackoverflow
Solution 15 - JavaKaz DragonView Answer on Stackoverflow
Solution 16 - JavaBill KView Answer on Stackoverflow
Solution 17 - JavaBrian T HannanView Answer on Stackoverflow
Solution 18 - JavavdboorView Answer on Stackoverflow
Solution 19 - JavauckelmanView Answer on Stackoverflow
Solution 20 - JavaHackerGilView Answer on Stackoverflow
Solution 21 - JavaPaul GregoireView Answer on Stackoverflow