If I have a property 'gId' in my Java class what should the accessor method be named as?
getGId is what I assume.
If there were a property gURL I think it would be getGURL, which kind of looks ugly (not referring to the alternative spelling of girl though).
If the property was just url the method name getUrl is good on the eye and yeah I would not name the property as URL in the first place which would make the accessor ugly again - getURL
I remember reading from the Javabean Specification PDF somewhere about capitalization of properties and also cases involving acronyms but cant find it in the PDF anymore.
Does anyone have a reference to it or please confirm if I am right in what I am saying?
The reference you are interested in can be found in the Beans specification at Section 8.8.
That being said, it does not explicitly cover your particular case of gId/gURL. The specification says that to provide a getter/setter, we simply capitalize the first letter. To recover the property from the getter/setter, if the first two letters are uppercase, then the whole property is left as-is. Otherwise we decapitalize the first letter. So your getter would become getGURL, but your property would be incorrectly recovered from the getter as GURL. You have the same problem with gId.
Therefore it seems that the specification does not allow you to provide a consistent translation of any property with a first lowercase character followed by an uppercase character.
My suggestion is to either adopt a completely lowercase property, or to extend the lowercase prefix to two letters (glURL, for example).
To be more concret (and as said by Luca and here), spec tells that there is a method which can tell you: java.beans.Introspector.decapitalize(String).
Related
if I have the following private member:
private int xIndex;
How should I name my getter/setter:
getXindex()
setXindex(int value)
or
getxIndex()
setxIndex(int value)
EDIT: or
getXIndex()
setXIndex(int value);
?
The correct answer is
getxIndex()
setxIndex(int value)
if you want them to be used as properties according to section 8.8: Capitalization of inferred names of the JavaBeans API specification (e.g. access them via ${object.xIndex} in a JSP.
In accordance with JavaBeans API specification from 1997
it should be as Thomas Einwaller describes:
// According to JavaBeans API specification
public int getxIndex() { return xIndex; }
public void setxIndex(int xIndex) { this.xIndex = xIndex; }
This is unfortunate, getx and setx are not words. In the rare case when this would form a word or acronym it would be disinformative, eg the method setiMessage most
likely has nothing to do with SETI.
Using the only valid measurement of code quality (WTFs per minute),
I assess that this is bad code.
If we modify this to follow the convention for
naming a method it would be:
// According to Java naming convention
public int getXIndex() { return xIndex; }
public void setXIndex(int xIndex) { this.xIndex = xIndex; }
Why does the JavaBeans specification violate the convention? It all comes down to this sentence of the JavaBeans specification:
However to support the occasional use of all upper-case names, we check if the first two characters of the name are
both upper case and if so leave it alone.
Exactly what kind of use of all upper-case names this refers to is unclear to me. Field names should, according to
convention, be camel cased. It seems
to me that we generate unconventional method names in order to support unconventional field names as decided by a
20+ year old document.
It should also be noted that even though it seems to be an overwhelming support for the JavaBeans specification in tools,
it is not exclusively used. Eg. Kotlin will not recognize xIndex as a property in the above example. Reversely, the
Kotlin property var xIndex = 0 will result in the Java methods getXIndex and setXIndex. This seems to be a bug
according to the JetBrains support, but I fail to see how they can fix that without making a breaking change.
Some tools that does support the JavaBeans specification has not always done so, eg Jackson
and Swagger Code Generator have been patched to conform to it.
Even though IntelliJ generate accessors according to the JavaBeans specification, the example
in the documentation differs from it. Probably because people don't know about the standard and naturally prefers the
normal method naming convention.
So when should we follow the JavaBeans specification? When property names should be inferred by accessors by tools that
rely on this standard, then we might want to use it. For instance, Jackson will rely
on the property xIndex being accessed through getxIndex and setxIndex methods unless we use annotations.
When should we avoid this standard? Per my recommendation: When the code should be read and understood by humans.
Because to not use proper camel casing when naming methods is disinformative.
If I would have it my way, we would use normal naming conventions, ie getXIndex and setXIndex. But, given the state
of things, the best solution I see is suggested by #vaxquis:
Name your field "indexX" or whatever else, your problem is solved... don't overcomplicate things - even if setxIndex
is the correct way for Beans, having method named setxIndex increases the WTF factor of the code without giving you
anything in return.
Any comments regarding the JavaBeans specification should, according the specification itself, be sent to
java-beans#java.sun.com.
Should be:
getXIndex()
setXIndex(final int xIndex)
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
You should use Introspector.decapitalize from package java.beans and you have no problem beacause it is compliant with java rules.
Eclipse ide automatically generates setters and getters as:
getxIndex()
setxIndex(int value)
Which is according to the java beans API specification.
I think getXindex() is the best way. The getter should start with 'get', followed by the member name, with its first letter capitalized. Also the latest conventions I heard of, say that we should avoid multiple capital letters one after another. For example getHTMLtooltip is wrong. it should be getHtmlTooltip instead. Also you should try to make all your members final and there should not be a need of setters, since the class will be immutable ;)
I am porting apitest to jogl, one of the directory is called Null, so I was simply trying to use null as package name and Netbeans complains that it is not valid.
I know I am splitting hairs, but I am just curious.. I didn't find anything here or on google..
Does it have to do with the reflection, the name retrieving, something similar or something else?
Or is it like this by design, same as operator overload?
Edit: I know it is a reserved word, but in code..
An identifier cannot be named null as the language specification mentions:
An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.
in this case, null is a literal (null literal)in java language, you can not used as identifier...
According to Oracle:
Naming Convention:
Package names are written in all lower case to avoid conflict with the
names of classes or interfaces.
...
In your case Following reference is important:
In some cases, the internet domain name may not be a valid package
name. This can occur if the domain name contains a hyphen or other
special character, if the package name begins with a digit or other
character that is illegal to use as the beginning of a Java name, or
if the package name contains a reserved Java keyword, such as "int".
In this event, the suggested convention is to add an underscore. For
example:
I believe it is like this only by design.
As per Java Language Specification, 'null' is a keyword and you cannot use any of the keywords to identify any other thing than its prime purpose.
Although you can use Null with capitalized 'N' and similar for all other keywords that does not match case with predefined keywords.
Java discourages use of such poor naming practices.
null is a value given to identifier. package is a identifier. it cannot be a value.
Today I was naming a package in a project which would contain code related to a concept called an "access structure".
Now, naming this package "com.myemployer.project.component.accessstructures" seems unappealing and difficult to read because of the triple "S". (The higher level packages are not actually named "project" and "component").
I was tempted to use "...component.access_structures"
I couldn't find anything mentioned in the Java conventions on Oracle's site . And a brief web search brought up nothing.
What is the official convention for names like this?
From Oracle Docs
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore
Although this text doesn't specify your exact case, it does say that for an invalid package name we should use an underscore. One could argue that accessStructures is how we would define a method in Java and thus naming a package like that could be confusing.
Overall, it is really up to you.
If you want to keep with this convention, I believe you should name your package:
com.myemployer.project.component.access_structures
Also you can look up synonyms and find alternatives that would give less confusion. Some I quickly found:
accessframework
accessfactory
accessarch (accessarchitecture)
accessconstructs
I dont think there is any standard for that. People follow different naming conventions as per there convenience and readability. But most of the programmers find camel case naming as the most convenient. You can name it like accessStructure
Found one Oracle Doc which recommends to use the package name with all small letters
Package names are written in all lower case to avoid conflict with the
names of classes or interfaces.
According to docs you can't use camelCase for package naming. It's ok to use snake_case for package naming in some cases, but it is more appropriate if you can't use your domain properly, because of the hyphen sign in it or it starts with numbers. But it has to be rather an exception from the rule than the rule.
If I were you I would rephrase it. For example: accessstructures -> accesscore
Please refer to Naming conventions for java methods that return boolean(No question mark)
to make a comparison about what I am NOT asking.
My question concerns properties derived from delegates embedded in a container object.
While the setters of all properties regardless of type is easily and conveniently prefixed with "set" (e.g. setValueRequired(blah) ), there are various types of boolean properties each whose getter is conventionally named {verb}{PropertyName}. e.g.,
the most common is existential, by convention is prefixed by "is". e.g. isEmpty().
possessive property, prefixed by "has", e.g. hasValue().
affirming necessity, prefixed by "requires", e.g. requiresResize(), providesResize().
By far, most property getters are somehow converted into existential properties. e.g. isRequireResize, isValued, etc. Therefore, my question concerns only expressing existential boolean properties (of a delegate class).
Let us say the container class is Printer, which contains the class Queue.
class Queue {
boolean empty, resettable, resizable;
}
class Printer {
Queue queue;
}
How then should Printer name its delegated properties for Queue? Because the following, by English comprehension convention, is awkward, as they sound like asking a question, not affirming its status.
isQueueEmpty()
isQueueResettable()
isQueueResizable()
The boolean property should be affirmative and not sound like asking a question. Therefore for comprehensible English, they should be
queueIsEmpty()
queueIsResettable()
queueIsResizable()
Or alternatively, could be
isEmptyQueue()
isResettableQueue()
isResizableQueue()
However, automated delegate method code generators invariably generate names isQueueEmpty(), isQueueResettable(), isQueueResizable().
That is awkward when placed into an if
if (isQueueResettable() && !isQueueEmpty()) resetQueue();
As this sounds better
if (isResizableQueue() && !isEmptyQueue()) resetQueue();
~
My Questions actually
If there a JSR recommending naming conventions of property getters? What is it? Certainly there must be, otherwise wouldn't all the code generators out there be limping around with ambiguous conventions?
If there is, does the JSR have recommendation for delegated boolean existential property getters?
If not JSR, at least some form of RFCs in Apache, JBoss, Eclipse, etc?
Don't you think the convention I recommend is better than code generators creating questioning getters?
I don't know much about JSR, but I am just trying to give my understanding.
You say isResettableQueue() sounds better than isQueueResettable to you( and probably to many others).
When you break up isResettableQueue() into is - Resettable - Queue, the main object(thing) about which you are talking comes into context at the last (in this case Queue).
But when you break up isQueueResettable() into is - Queue - Resettable, the main object(thing) about which you are talking comes into context at early stage (at least not at the last.
So you can tell Ok now I am talking about Queue for which I am checking if it is empty
Method names should start with a verb, so queueIsEmpty shouldn't be used.
I can't find any articles about naming conventions that mention this particular case, but the most natural choice would still be isQueueEmpty. isEmptyQueue would refer to this instead of this.queue. It would return whether "This object is an empty queue" instead of "This object's queue is empty".
Oracle also uses method names on the form isQueueEmpty.
Here are relevant method names defined in AbstractButton, JFrame, JTable and their super-classes:
isAlwaysOnTopSupported, isBackgroundSet, isBorderPainted, isCellEditable, isCellSelected, isColumnSelected, isContentAreaFilled, isCursorSet, isFocusPainted, isFocusTraversalPolicySet, isFontSet, isForegroundSet, isMaximumSizeSet, isMinimumSizeSet, isOptimizedDrawingEnabled, isPreferredSizeSet isRequestFocusEnabled, isRolloverEnabled, isRootPaneCheckingEnabled, isRowSelected
Actually this is completely theoretic question. But it's interesting why java specification don't allow uppercase characters letters in package and cause write something like this:
com.mycompany.projname.core.remotefilesystemsynchronization.*
instead of
com.myCompanyName.projName.core.remoteFileSystemSynchronization.*
Directly from Oracle Docs
Package names are written in all lower case to avoid conflict with the
names of classes or interfaces.
But it's interesting why java specification don't allow uppercase characters letters in package and cause write something like this:
The specification allows it just fine. It's only a convention to use all-lower-case.
As gtgaxiola says, this does avoid conflict with type names... in .NET naming conventions this does happen, leading to advice that you do not name a class the same as its namespace. Of course, using camelCase packages would avoid the collision entirely.
I suspect reality is that it wasn't thoroughly considered when creating the package naming conventions. Personally I rarely find it to be a problem - if I end up seeing a package with one element of "remotefilesystemsynchronization" then the capitalization isn't the main thing I'd be concerned about :)
Its just another convention - One may ask why class name always has to start with Capital or method name starts with small case and then camel-cased. Java doesn't forces you to use that way. Its just that a set of underlined rules helps huge community as Java developers to write easily understandable code for the majority who follow conventions.
No definite reason can be assigned as such. Its just what felt good and was in practice by then majority programmers while writing the convention. But yes guidelines would definitely be there before writing conventions. I don't mean its a whimsical work. Guidelines are made so that just by looking at the various elements we should be able to tell if its class, method or package - and via following conventions it has been achieved for so long now.