Long method names java

When is a Java method name too long?

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

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

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

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.

  • 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)
 @Test public void testDialogClosesDownWhenTheRedButtonIsPressedTwice()

See «Behavior Driven Design» for more info on this idea.

Читайте также:  Pear classes in php

Solution 5

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.

How to fix Path Too Long and File Name is Too Long errors in Windows

Methods in Java Tutorial

025 - Jersey Hello World Example

Fix Destination Path Too Long Error In Windows 10/8/7

How To Create Variables That Don't Suck - Writing Clean Java Code

Java - How to name methods, classes and variables

Java Naming Conventions

Java Arrays | QO-BOX

Java Training Day 31 | Java Full Course | Coding Skills

How to Break Java with a Ridiculous Variable Name

main(String[] args) method in Java | static mechonism | static keyword

Intro To Methods In Java

MexicanHacker

Trying to learn something new every day.

Updated on October 10, 2020

Comments

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 

@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, 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.

matbrgz

@yar, the link you gave referred to the length of the method in lines, not the length of the method name.

@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 😀

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.

@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.»

Erethon

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.

Ponkadoodle

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

nanofarad

You can shorten your method names however much you want but InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMax‌​imizeButtonPainter.q‌​() will still be absurd.

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

Jorjon

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?

Ricket

Rémi Vennereau

So, for example, boolean doesShorterNameExistThatEquallyConvaysTheBehaviorOfTheMethod‌​(String s) should be refactored to boolean isTooLong(String s) .

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 .

additionally, 5) will put getEligibleItems() and getEligibleItemsCount() next to each other in alphabetically ordered lists (e.g. autocompletion or javadoc)

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

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

sal

Looks like that class was named by the naming people hired by the Department of Redundancy Deparment to name things at the Department of Redundancy Department.

sal

Bill

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

What about abbreviations? They will convey the exact same thing as the non-abbreviated version, but are often harder to read.

What?! I don’t see why I was downvoted for this. The question didn’t ask for a necessary condition, just a sufficient one!

Technically, the Java language spec doesn’t have an upper limit for identifier length. This is a limitation of your JVM implementation. Cheers!

As you can tell from the best-scoring answer above, go for outback simplicity instead of OO advice. +1

@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.)

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

ammaciel

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

Источник

Longest Class, Method and Attribute Names in Java

Just got curious to see what is the longest class name in Java JDK bundle and extended that curiosity to method and attribute names as well.

Wrote a tiny Java program to load all classes, their methods and attributes from a Jar to print their name to a file. Then ran that on JDK 1.6 (rt.jar) and got the following results.

  • For class name the award goes to (92 chars) InternalFrameInternalFrameTitlePaneInternalFrameTitlePane MaximizeButtonWindowNotFocusedState
  • For method name the award goes to (66 chars) localizableRUNTIME_MODELER_PORTNAME_SERVICENAME _NAMESPACE_MISMATCH belonging to class ModelerMessages.
  • For attribute name the award goes to (60 chars) ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX _FOR_DEFAULT belonging to class XSLTErrorResources.

long

Hope you are following naming conventions strictly in your projects. I welcome you to run this below program on your project or your favorite packages like Spring / Hibernate etc and share your interesting findings in the comments.

This Java program will print all the class, method and attribute names from the Jar file, sorted in descending order of length.

package com.javapapers.java; import java.io.File; import java.io.PrintWriter; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class LongNames < public static void main(String[] args) throws Exception < String javaFile = "C:\\Program Files\\Java\\jdk1.6.0_24\\jre\\lib\\rt.jar"; ListclassList = new ArrayList(); List methodList = new ArrayList(); List attributeList = new ArrayList(); System.out.println("Processing. "); getList(new File(javaFile), classList, methodList, attributeList); sort(classList); print(classList, new PrintWriter("ClassList.txt")); System.out.println("Class list complete."); sort(methodList); print(methodList, new PrintWriter("MethodList.txt")); System.out.println("Method list complete."); sort(attributeList); print(attributeList, new PrintWriter("AttributeList.txt")); System.out.println("Attribute list complete."); > private static void getList(File file, List classList, List methodList, List attributeList) throws Exception < EnumerationjarEntries = new JarFile(file).entries(); while (jarEntries.hasMoreElements()) < JarEntry jarFile = jarEntries.nextElement(); String className = jarFile.getName(); if (className.endsWith(".class")) < className = className.replaceAll("\\.class", ""); className = className.replaceAll("/", "."); try < if (className != null && !className.isEmpty()) < Class clazz = Class.forName(className, false, ClassLoader.getSystemClassLoader()); // inner class hack if (clazz.getSimpleName().length() >0) < classList .add(new Content(clazz.getSimpleName(), "")); getMethodList(clazz, methodList); getAttributeList(clazz, attributeList); >> > catch (Exception e) < System.out.println(e); >> > > private static void getMethodList(Class clazz, List methodList) < Method[] methods = clazz.getMethods(); for (Method method : methods) < methodList .add(new Content(method.getName(), clazz.getSimpleName())); >> private static void getAttributeList(Class clazz, List attributeList) < Field[] fields = clazz.getFields(); for (Field field : fields) < attributeList.add(new Content(field.getName(), clazz .getSimpleName())); >> private static void sort(List nameList) < Collections.sort(nameList, new Comparator() < public int compare(Content c1, Content c2) < //descending return c2.content.length() - c1.content.length(); >>); > private static void print(List list, PrintWriter file) < for (Content str : list) < file.println(str.content.length() + "\t" + str.content + "\t" + str.className); >file.close(); > > class Content < public Content(String content, String className) < this.content = content; this.className = className; >String content; String className; >

Comments on «Longest Class, Method and Attribute Names in Java»

According to the naming conventions, its good to follow this. But my doubt is why they have restricted to this specific length? Is there any reason behind this? Thanks,
Nagendra.

92 chars for class name,it is restricted,we can not go beyond to it.if this is restricted how did you calculate it?Is class name length dependent on JDK version?

One suggestion, your site template has very limited space for text/code. This makes difficult to scroll sidewise to understand code. I appreciate your posts and interest.

Yes Praveen, thats right. Presently, I am working menu redesign and I will fix this also along with that.

Hi Joe I tried to find in javadocs this class InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState. I see none. Why? What is the use of this class? Regards
Jinu

It worked but got different results , I made some changes I used rt.jar which is in jre7 library as I don’t have java installed.
Thanks

Comments are closed for «Longest Class, Method and Attribute Names in Java».

Источник

Оцените статью