What should we expect from the following name? : mGage Program
if I camelCase this it will be mGageProgram and if I generate (in eclipse) the getters and setters I will get the following:
public String getmGageProgram() {
return mGageProgram;
}
public void setmGageProgram(String mGageProgram) {
this.mGageProgram = mGageProgram;
}
Which to me doesn't seem right as I was expecting the getMGageProgram() and setMGageProgram(value).
Are these getters/setters names alright?
According to 8.8: Capitalization of inferred names of the JavaBeans API specification
the names generated from the IDE are correct.
they are 100% correct :) but conventions differ among programmers , for me its method names in camel casing not variables. as for syntax its correct :)
I’d like to provide just a little more depth on what the spec says. It specifies how we get from the name of a getter and/or a setter to a property name. The interesting quote in this context is:
… 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.
It’s from section 8.8: Capitalization of inferred names.
One example given is that URL (as in getURL or setURL) becomes (or stays) URL (not uRL).
So the method names that you and I would have expected, getMGageProgram and setMGageProgram, would have implied a property named MGageProgram with an upper case M. Since we wanted mGageProgram we need to use lower case m in the names of the getter and the setter.
The rules as I read them thus really allow you to use a lowercase letter right after get or set in any getter or setter name. This came as a peculiar surprise to me. Of course it’s not an option that we want to exploit in cases where we don’t have to.
Link: JavaBeans Spec download page
Related
How do you name a class when it's all caps in Java? For example, if I want to create a class to select certain people to be VIP. Should I name the class "VIPSelector" or "VipSelector"?
Thanks!
Both of your options work. The main goal with classes is to have them start with an Upper Case. So, VIPSelector and VipSelector both work. This convention is mostly used to get rid of a common mistake that you can find in OOP which is when you can't make the difference between a class and a method.
Imagine having a class object called "student", to initiate it, it would be
student s = new student();
That looks a lot like a method and this is why, by convention, we put the first letter in upper case.
This is how class Name should be :
Class names should be nouns, in mixed case with the first letter of
each internal word capitalized. Try to keep your class names simple
and descriptive. Use whole words-avoid acronyms and abbreviations
(unless the abbreviation is much more widely used than the long form,
such as URL or HTML).
Examples: class Raster; class ImageSprite;
Check this for the information : https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html#:~:text=Class%20names%20should%20be%20nouns,such%20as%20URL%20or%20HTML).
Both names are acceptable. The general convention for naming classes in Java is just that the first letter should always be capitalized and the whole name should be in camel case, meaning that the first letter of each word is capitalized.
The google style guide prefers VipSelector
See this answer to a similar question.
I want to create a package named form validator.
Is it better to write
form_validator,
formValidator or
formvalidator?
I want to mention that I want to avoid form.validator. And that form-validator is forbidden.
From the documentation on package naming convention:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces
So this would leave you with the following two possibilities:
form_validator
formvalidator
Actually the documentation also makes it clear that underscore plays a special role when it appears in package names:
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" ... the suggested convention is to add an underscore.
So, underscore is suggested only in special cases, into which your naming problem does not seem to fall. So I would recommend formvalidator as the package name.
The most conventional one would be the 3rd one: formvalidator.
The Google Java Style guide notes:
5.2.1 Package names
Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.
As #teppic said, the Oracle Java Docs state that
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
In Java package names are written in all lower case. Which means following would be the most ideal packaging name.
formvalidator
This is also accepted.
form_validator
Package names are written in all lower case to avoid conflict with the names of classes or interfaces. So
form_validator or
formvalidator.
For details see here.
The Java Language Specification states that a normal annotation is in the format
NormalAnnotation:
# TypeName ( ElementValuePairsopt )
A single-element annotation is in the format:
SingleElementAnnotation:
# Identifier ( ElementValue )
I do not understand, why this inconsistency, why is a normal annotation a TypeName and a single element annotation an Identifier? I believe the reference to Identifier might be a mistake in the specification since Identifier is not qualified and javac accepts AnnotationDeclarations that are qualified, for both normal annotations and single element annotations.
The reference to Identifier is a mistake in the specification since an identifier cannot be qualified (you can write #java.lang.SuppressWarnings("unchecked") but java.lang.SuppressWarnings is not a legal identifier). Javac accepts AnnotationDeclarations that are qualified, for both normal annotations and single element annotations. The mistake appears to be recently introduced; older versions of the JLS do not have this problem.
I think there is a mistake in the grammar documentation. The single annotation-element and the marker annotations are shorthand for the normal annotation.
You can also see the Java 1.5/1.6 specification: http://docs.oracle.com/javase/specs/jls/se5.0/html/interfaces.html#9.7
The single-element annotation is indicated as:
SingleElementAnnotation:
# TypeName ( ElementValue )
The tutorial is stating that Identifiers and TypeNames are two different things. From a programming perspective they are not. But from a logical perspective they could be, with the right analogy.
Starting with TypeName: Data types (Not counting primitive) and classes usually have more than one methods and/or attributes. So in a way, TypeName is kind of like the name of a class or a data type, which it kind of is.
On to Identifier: An Identifier is used to name or describe ONE variable or ONE class. In the right context, an Identifier can be associated with a single thing, like a int value, while a TypeName can represent an int and a String in one class.
int Identifier = 90; //Identifier represents an int value
class TypeName{
int i;
String s;
} //TypeName represents an int value and a String
TypeName MyNew = new TypeName(); //MyNew references to a TypeName, holding more
//than one value
This is very discreet logic, so if the logic does not make sense to you at first glance, the author may have changed the names for clarity, to make them a bit different. But no matter what the author calls them, they are the same thing, just worded differently.
It's a matter of semantics (and fairly pedantic semantics at that).
Consider a NormalAnnotation, such as #SuppressWarnings(value={"foo","bar")), where the SuppressWarnings (the TypeName) resolves to an annotation class that has a member named value.
Now consider a SingleElementAnnotation, such as #SuppressWarnings({"foo","bar")). The Identifier (SuppressWarnings) is the name of an interface, but there is nothing that says the one parameter should be assigned to value.
So, you cannot directly parse that sequence of characters as a NormalAnnotation; it doesn't have a correctly formatted ElementValuePairs. However, if you insert value=, between the opening parenthesis and the start of the parameter, then you get something that is parseable as a NormalAnnotation.
Likewise for MarkerAnnotation. It is missing the parenthesis required by the NormalAnnotation.
The Identifier needs to be a value that when used in the NormalAnnotation will yield a TypeName.
The NormalAnnotation has a number of restrictions on it, such as:
It is a compile-time error if TypeName does not name an annotation type that is accessible (§6.6) at the point where the annotation is used.
Until the SingleElementAnnotation or MarkerAnnotation is transformed into a NormalAnnotation, SuppressWarnings is just an Identifier and only needs to conform to the definition of Identifier. Note that TypeNames can be qualified, such as java.lang.SuppressWarnings, but Identifiers cannot.
I believe the intent was that MarkerAnnotation and SingleElementAnnotation should use simple names (Identifiers) rather than fully qualified names (TypeNames). So technically speaking #Override is ok, #java.lang.Override is incorrect, but #java.lang.Override() would be allowed. Every compiler I can get my hands on allows the latter. That makes the distinction rather moot for nearly everyone.
In some interfaces I wrote I'd like to name generic type parameters with more than one character to make the code more readable.
Something like....
Map<Key,Value>
Instead of this...
Map<K,V>
But when it comes to methods, the type-parameters look like java-classes which is also confusing.
public void put(Key key, Value value)
This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from Sun or a general best-practice.
Alternatives I guessed or found...
Map<KEY,VALUE>
Map<TKey,TValue>
Oracle recommends the following in Java Tutorials > Generics > Generic Types:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this lesson.
I'd stick to it to avoid the confusion among the developers and possible maintainers.
Append Type
A good discussion can be found in the comments on the DZone page, Naming Conventions for Parameterized Types.
See the comment by Erwin Mueller. His suggestion makes perfect obvious sense to me: Append the word Type.
Call an apple an apple, a car a car. The name in question is the name of a data type, right? (In OOP, a class essentially defines a new data type.) So call it a “Type”.
Mueller’s example, drawn from the original post’s article:
public interface ResourceAccessor < ResourceType , ArgumentType , ResultType > {
public ResultType run ( ResourceType resource , ArgumentType argument );
}
Append T
A duplicate Question provides this Answer by Andy Thomas. Note the excerpt from Google’s style guide that suggests a multi-character type name should end in a single uppercase T.
Yes, you can use multi-character names for type variables, as long as they are clearly distinguished from class names.
This differs from the convention suggested by Sun with the introduction of generics in 2004. However:
More than one convention exists.
Multi-character names are consistent with other Java styles, such as Google’s style for Java.
The readable names are (surprise!) more readable.
Readability
In some interfaces I wrote I’d like to name generic type parameter with more than one character to make the code more readable.
Readability is good.
Compare:
public final class EventProducer<L extends IEventListener<E>,E>
implements IEventProducer<L,E> {
to:
public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT>
implements IEventProducer<LISTENER, EVENT> {
or, with Google’s multi-character convention:
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
Google style
The Google Java Style Guide allows both single-letter names and multi-character class-like names ending in T.
5.2.8 Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT, FooBarT).
Issues
“Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.” – from the Oracle tutorials, “Generic types”
Single-character names are not the only way to distinguish type parameters from class names, as we’ve seen above.
Why not just document the type parameter meaning in the JavaDoc?
It’s true that the #param JavaDoc elements can provide a longer description. But it’s also true that the JavaDocs are not necessarily visible. (For example, there’s a content assist in Eclipse that shows the type parameter names.)
Multi-character type parameter names don’t follow the Oracle convention!
Many of Sun’s original conventions are followed nearly universally in Java programming.
However, this particular convention is not.
The best choice among competing conventions is a matter of opinion. The consequences of choosing a convention other than Oracle’s in this case are minor. You and your team can choose a convention that best meets your needs.
You can use javadoc to at least give users of your generic class a clue. I still don't like it (I agree with #chaper29) but the docs help.
eg,
/**
*
* #param <R> - row
* #param <C> - column
* #param <E> - cell element
*/
public class GenericTable<R, C, E> {
}
The other thing I have been known to do is use my IDE to refactor a class breaking the convention. Then work on the code and refactor back to single letters. Makes it easier for me anyway if many type parameters are used.
The reason why the official naming convention reccommends using single letter is the following:
Without this convention, it would be difficult to tell the difference
between a type variable and an ordinary class or interface name.
I think with modern IDEs that reason is no longer valid as eg. IntelliJ Idea shows generic type parameters with different colors than regular classes.
Code with generic type as displayed in IntelliJ Idea 2016.1
Because of that distinction I use longer descriptive names for my generic types, with same convention as regular types. I avoid adding prefixes and suffixes such as T or Type as I consider them unnecessary noise and no longer needed to visually distinguish generic types.
Note: As I am not a user of Eclipse or Netbeans, I do not know whether they offers a similliar feature.
If a class contains a variable named "blah", then the standard getter/setter syntax is obviously getBlah() and setBlah(). But if I have a POJO class with a variable named isBlah, would I use:
public type getIsBlah() {
return isBlah;
}
public setIsBlah(type isBlah) {
this.isBlah = isBlah;
}
Or would it be this?
public type isBlah() {
return isBlah;
}
public setBlah(type blah) {
this.isBlah = blah;
}
The first seems to conform more strictly to the POJO conventions, but the second type is what IntelliJ generates if I ask it to make a class' getter/setters (and hey, IntelliJ has never let me down yet :] ). So which is the preferred syntax?
One reason for using properties is to decouple the API from the implementation. In other words, you shouldn't feel bound by what your private variable is called. That shouldn't inform the naming beyond trying to keep it readable to code maintainers.
I would say that if "type" is boolean in this case, then the second form is correct. If it's not boolean, you should use getXXX - but I probably wouldn't use getIsXXX. To me, "is" has a very strong correspondence with Boolean properties, and using it in other contexts would not only break the JavaBeans conventions (which could affect other tools) but would be misleading IMO.
Note that the name of the field is completely irrelevant to the JavaBean specification. Only the names of the getter/setter are relevant.
Normally the name of the getter is get<PropertyName>(). Only for boolean properties is is<PropertyName>() allowed as an alternative.
Note that in your example the Bean property name is "Blah" when you call the getter isBlah() and it's "IsBlah" when you call your getter getIsBlah().
Personally I usually prefer isBlah().
Wouldn't say there's a strong convention for POJOs, but for JavaBeans the second (IntelliJ) example is the standard for boolean attributes, everything else uses getX.
There's one big problem with the "is" syntax if you use JSTL, which is that JSTL EL doesn't recognise them. It's pretty stupid, but the designers of the JSTL EL didn't bother to check their logic for javabeans compliance.
I often find myself writing getIsBlah() methods in my view-layer classes, which call isBlah(), just to give JSTL a hook. It's horrible.
I would also choose your second option. The first, with getIsBlah() seems wordy and redundant.
Both the "get" and the "is" is fine actually, as they are technically still acceptable under the JavaBeans convention. I'd go for whichever sounds better or more natural, depending on what word your "Blah" actually is.
JSTL only allows isMyBool if it is a boolean, not a Boolean or any other object, as per the bean spec. (primitive vs object).