Naming convention for member variables with initials - java

I was wondering how someone would name the member field that began with initials as opposed to words.
public class MyClass {
// I know this is how it is for a member field with words.
private String myString;
// What about this String? It is representing the term "RV Scale" which is
// short for "Reclose Volts Scale."
private String RVScale;
}
I know that I could just use private String recloseVoltsScale, but I'd rather keep it RVScale. If anyone knows if its supposed to be rVScale or RVScale or something else I'd appreciate the info.
EDIT :
Also, what about a member field like this...
private int RV;

as per java naming convention member field should start with mixedcase so it should be rvScale and member field like RV should be like private int rv;
Using the right letter case is the key to following a naming convention:
Lowercase is where all the letters in a word are written without any capitalization (e.g., while, if, mypackage).
Uppercase is where all the letters in a word are written in capitals. When there are more than two words in the name use underscores to separate them (e.g., MAX_HOURS, FIRST_DAY_OF_WEEK).
CamelCase (also known as Upper CamelCase) is where each new word begins with a capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).
Mixed case (also known as Lower CamelCase) is the same as CamelCase except the first letter of the name is in lowercase (e.g., hasChildren, customerFirstName, customerLastName).

You should spell it out.
That being said, I would keep it rvScale.
Keep in mind that the only one that should NOT be used is rVScale since this can cause some confusion with introspection.
This case would generate getter and setter named getRVScale and setRVScale, but using bean introspection to find the property associated with these, would search for a property named RVScale, which doesn't exist. This is due to the fact that when searching for the corresponding property, the first letter after the get/set is lower cased, unless there are two adjacent letters in upper case (RV), in that case, the name is left as is, producing RVScale.
Like explained here:
Javabean convention - method naming for property gId

Do not use shortcuts unless you need to. Even if they are private (or maybe because they are), name variables clear enough. If potential code reader does not understand rv as shortcut of something like Reclose Volts, do not use shortcut. If you need provide hint it is shortcut actually, you are hinting he should lookup it somewhere what does that mean. Where will he find it? If it is in comment, you have wrong name of member, as you have to explain what does the name mean. Unless you application is all about Reclose Volts. I suggest to follow java conventions as they did have reason to appear.

Related

Using + in a java enum type

I'm fairly new to Java and I'm trying to use the + character as part of an enum type, but the compiler is complaining about the syntax because I believe it sees it as an operator.
I'd like to do the following:
enum mediaType{
FACEBOOK,GOOGLE+,TWITTER;
}
Any ideas?
Thanks!
Yes, the compiler will treat + as an operator. You can however choose a different name there:
enum mediaType{
FACEBOOK,
GOOGLE_PLUS,
TWITTER;
}
And if you want to use the value GOOGLE+ only, then have a field of type String, storing the value, and also a parameterized constructor.
P.S: As per proper naming convention, the enum name should be MediaType.
You can't use arithmetic symbols in identifiers. You need to find something you can use like GOOGLE_PLUS
Maybe reading the official Java tutorial's section on Naming Conventions will help you: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
You could at least define a private String myName = "Google+"; inside the enum, and define a method that a UI can use to get the value you want rather than just displaying the enum's variable itself.
public String myName() {
return myName;
}
Many people believe that you are limited to ASCII in Java just like C and C++.
Actually you have the full Unicode character set.
This is perfectly good Java:
enum Plus {
Google,
GooglePlus,
Googleᚋ,
Googleᐩ;
};
Not quite a + (which you cannot have in an enum because it will be confused with the + operator) but it will still carry the impression of a plus.
It seems you can use the Ogham character called muin which looks a bit like a plus character. Alternatively it seems the Canadian syllabics final plus is also acceptable alhough a number of the other possibilities seem not to be acceptable.

Can we use type names as variable

I've been wondering about this question for a long time :
Can we use a type name as a variable name ?
For example someone on a REST api called one of its variable "protected", is there a way to get it ? I'm developing an Android app, and the api return Json object. To accelerate the process i use the Gson library.
Its mentioned in the Docs already that
You cannot use any of the following as identifiers in your programs.
And wiki says
programmers cannot use keywords as names for variables, methods, classes, or as any other identifier.2
If still you want to use them add underscores or some extra letters to that name.
No. Please, read this list of reserved words for Java http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
But, if I remember right, in Gson you can mark variable by annotation with name of element in Gson - it can helps you.
In Java Language Specification:
3.8. Identifiers
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.
However in Java Virtual Machine Specification:
4.2.2. Unqualified Names
Names of methods, fields, and local variables are stored as unqualified names. An unqualified name must not contain any of the ASCII characters . ; [ / (that is, period or semicolon or left square bracket or forward slash).
So
You can't use a type name as a variable name in the Java Language
You can use a type name as a variable name in class file.

java variable names

Could you give some good reasons for having the class name as part of the name of any variable? We use to have this policy, which I find quite useful. Some team member wants to revert the decision.
My arguments for the moment:
you can directly know what you're talking about:
for (Student student: students) {
...
}
is quite easy to understand (vs Student s or Student anyone)
it helps self-commenting the code
our ide provides direct support for that
you can directly see wheter you're using apples instead of pears (or bears ;-) )
Less confusion where subtle differences matter:
criteriaBuilder.equal(nameExpression, name);
The only argument I can see against this is that it makes the code longer (which I think isn't an issue with modern IDEs).
Is there public provisioning for such a recommendation? Anyone using the same rule? Any alternative?
That sounds like Hungarian Notation to me.
In principle it sounds like a good idea but I'm honestly not sure there are good reasons for it:
Self commenting / documenting code - this should be possible without putting types in the variable names;
An IDE should also provide support for seeing what type a variable is without putting it in the variable name (e.g. Eclipse can do this)
I don't know that this is really an advantage.
One problem with Hungarian Notation that you don't mention is that if you refactor code, you have to change all the variable names as well. There are plenty of examples on The Daily WTF where variables are named 'strSOMETHING' or 'intSOMETHING', even though the types are defined as something else.
In general, IMO the case for using Hungarian Notation is pretty flimsy and generally I wouldn't recommend making it a policy.
(If this isn't exactly what you are talking about, I apologise!)
Your bible on this question is Steve McConnel's book, Code Complete, which is the most comprehensive book on software construction practice like this. He has a whole chapter on variable naming and why it is important.
The key is to make the name a full description of what the variable does, so that it is easy to understand for the person reading it. If it achieves that, then it's good practice.
Student student looks like a simple to understand policy, but it has an immediate disadvantage - it contains no extra information about the variable. You already know its a student. If you know anything else about the object then add it to the variable name - studentUnderReview, graduatingStudent etc. "student" should only be used if you know absolutely nothing else, such as the variable is used to iterate over all Students. Now in a long method it's useful to know the type by just looking at the name, but if the variable has short scope then it's marginal whether its useful or not. There are some studies (see McConnel) which indicate that for variables with very short scope, such as for loop indices, short names are better.
As soon as you have two variables, this system breaks down. If the default is to call one variable "student" then the temptation is to call two variables "student1" and "student2", which is bad practice indeed (see McConnel for details). You need to make names that describe the object - goodStudent and badStudent; studentBeingSaved and studentBeingRead.
The policy should be to use descriptive variable names. One-letter variable names are bad, but so are variable names based exclusively on class names. Your main argument is really for descriptive variable names.
As for the others:
it helps self-commenting the code - no, it duplicates information from the variable declaration
our ide provides direct support for that - that would only be an argument if the alternatives provide no benefits
you can directly see wheter you're using apples instead of pears (or bears ;-) ) - that's the job of the type system
Of course, if your class names are descriptive, then sometimes it will make sense to have variables with the same name - when the variable describes an instance of the class without any distinctive characteristics. As in your example:
for (Student student: students) { ... }
If you're looping over all students, this is fine. But if you have a non-generic instance of Student, the variable name should describe what particular role that student has in this part of the program (e.g. candidate or graduate).
Generally your variable names should help the developer see quickly what they actually represent.
Student student would be ok if the relation that defines expresses a anything-to-student relation, like Student[] students (or better some collection of Student) would be ok for a class Professor or the like.
String string is generally a bad idea, since it doesn't say anything about the use of that variable. Better names would be String name, String description or similar. In some cases, where all that matters is that you're dealing with one string - like general string utilities - you might call the variable string but if you have two or more, you should use better names (e.g. source and target etc. depending on the class/method).
IMHO, adding prefixes/suffixes might be a good idea if they tell you something about the variable that its base name wouldn't, e.g. in a web environment you might deal with strings that are input by the user as well as escaped strings (e.g. to prevent code injection), so you might use a prefix/suffix to make a disctinction between the user input version and the escaped counterpart.

Am I misunderstanding the JavaBean method naming convention or is this an anomoly?

I have mysterious happenings in my code. Here's the snippet from the bean:
public List<HelpContentsFrag> getCFrags()
{
return cFrags;
}
public void setCFrags(List<HelpContentsFrag> frags)
{
cFrags = frags;
}
Here's the snippet from my view code (tag file)
cFrags:[${topic.cFrags}]
where topic is an object of the bean type.
Here's the error:
javax.el.PropertyNotFoundException: Property 'cFrags' not found on type com.company.beans.BeanClass
One additional thing to consider. There is a subtle difference in the eclipse-generated setter. Apparently, it didn't like the name cFrags either. The field name is cFrags and with every other setter I get parameter with the same name as the field and it is set using the convention this.fieldName = fieldName. You'll notice that eclipse did not stick with that on this setter.
FYI: this all works great when I change the getter to getContentsFrag() and reference it .contentsFrag.
I believe you want:
cFrags:[${topic.CFrags}]
With a capital C. See JavaBeans Spec:
8.8 Capitalization of inferred names.
When we use design patterns to infer a property or event name, we need to decide what rules to follow for capitalizing the inferred name. If we extract the name from the middle of a normal mixedCase style Java name then the name will, by default, begin with a capital letter. Java programmers are accustomed to having normal identifiers start with lower case letters. Vigorous reviewer input has convinced us that we should follow this same conventional rule for property and event names.
Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case. 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. So for example,
“FooBah” becomes “fooBah”
“Z” becomes “z”
“URL” becomes “URL”
We provide a method Introspector.decapitalize which implements this conversion rule.
To quote the JavaBeans specification (last updated in 1997):
Thus when we extract a property or
event name from the middle of an
existing Java name, we normally
convert the first character to lower
case. 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.
That describes how method names are converted to property names. What's not so clear is that the Introspector produces a single table that's used by property->method lookups as well.
You've already discovered one way to avoid the problem. Another is to create a BeanInfo class that contains the correct property->method mappings (the Introspector doc describes how to do this).

Why is it wrong to use numbers in Java method names?

Sometime ago, I remember being told not to use numbers in Java method names. Recently, I had a colleague ask me why and, for the life of me, I could not remember.
According to Sun (and now Oracle) the general naming convention for method names is:
Methods should be verbs, in mixed case
with the first letter lowercase, with
the first letter of each internal word
capitalized.
Code Conventions of Java
This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised.
Consider the situatiuon (that my colleague has) where you want to perform some logic based on a specific year, for instance, a new policy that takes affect in 2011, and so your application must act on the information and process it based on it's year. Common sense could tell you that you could call the method:
boolean isSessionPost2011(int id) {}
Is it acceptable to use numbers in method names (despite the wording of the standard)? If not, why?
Edit: "This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised." Perhaps I worded this incorrectly. The standard says 'Methods should be verbs'. I read this to say that considering a number is not a verb, then method names should not use numbers.
The standard Java class library is full of classes and methods with numbers in it, like Graphics2D.
The method seems ... overly specific.
Couldn't you instead use:
boolean isSessionAfter(int id, Date date)
?
That way the next time you have a policy applied to anything after a particular date, you don't need to copy-paste the old method and change the number - you just call it with a different date.
Sure, it's acceptable to use numbers in method names. But as per your example, that's why it's generally frowned upon. Let's say that there is now a new policy in place for the year 2012. Now, there's a new policy in place for 2014. And maybe 2020! So, you have four methods that are roughly equivalent.
What you want isn't a boolean but rather a strategy to do something, or do nothing, based on whether or not a policy was found. Hence, a method void processPolicy(Structure yourStructure); would be a better approach - now you can shield that you're doing a lookup based on the year, and don't have to have separate methods per year, or even limit it to just one policy per year (maybe a policy takes place in two different years, for example, or just three months).
The Java Language Specification seems fairly specific on this topic:
3.8 Identifiers
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
...
The Java letters include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.
The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).
This doesn't specifically say that numbers can't be used, although by omission you can see that it's not advised.
I certainly wouldn't read the Java Style Guide that way. And judging from numerous examples in the Java class libraries, neither do they.
I guess the only caveat is that the JSG recommends use of meaningful names. And the corollary is that you should only use numbers in identifiers when they are semantically meaningful. Good examples are
"3D",
"i18n" ( == internationalization ),
"2020" (the year),
"X509" (a standard), and so on.
Even "int2Real" is meaningful in a folksy way.
UPDATE
#biziclomp has raised the case of LayoutManager2, and claims that the 2 conveys no meaning.
Here's what the javadoc says about the purpose of this interface:
This minimal extension to LayoutManager is intended for tool providers who wish to the creation of constraint-based layouts. It does not yet provide full, general support for custom constraint-based layout managers.
From this, I would say that the 2 in the name is meaningful. Basically, it is saying that you can view this as a successor to LayoutManager. I guess that could have been said in words, but see the examples above on how numbers where numbers are used as short-hand.
# BlueRaja writes:
The 2 does not explain anything - how is LayoutManager2 any different from LayoutManager?
The advice of the Style Guide is NOT that names should explain things. Rather, it advises that they should be meaningful. (For the explanation, refer to the javadoc.) Obviously meaningfulness is relative, but there is a practical limit on the amount of information you can put into an identifier before it becomes hard to read and hard to type.
My take is that the identifier should remind the reader what the meaning of the thing (class, field, method, etc) that is named.
It is a trade-off.
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
This phrasing alone already shows that they use a more general meaning of verb than the usual, where only is would be the verb, neither session nor post are verbs. The sentence means something like Method names should be verbs or verbal phrases, ..., and numbers can very well be parts of verbal phrases.
The idea is that a complete method call can be read as a complete sentence, with the subject being the object before the dot, the verb being the method name, and additional objects being the arguments to the method:
if (buffer.isEmpty())
buffer.append(word);
(Most such sentences would be either questioning or imperative ones.)
Your method name has (from a naming convention viewpoint) the only problem that the subject of the sentence (the session) is not the this object of your method, but an parameter, but this can't be avoided with Java, I think (please someone prove me wrong).
For multiple-parameter methods the smalltalk approach would work better:
"Hello" replace: "e" with: "x"
(where replace:with: is one method of the string class.)
Yes, in some circumstances. For example, maybe you want to handle X.509 certificates. I think it would be perfectly acceptable to write a method called handleX509Certificate.
The only problem I see with using numbers in method names is that it may be an indication that something in your design could be improved upon. (I hesitate to say "is wrong.") For instance, in your example, you stated that you have a specific policy which comes into effect after 2011. However, having a method specifically to check for that year seems overly specific and magic-number-y. I'd instead suggest creating a generalized function to check if an event occurred after a specified date as Anon suggested.
(Anon's answer popped up while I was halfway through mine, so my apologies if it seems like I'm just duplicating what he said. I felt that mine expanded on what he was saying a bit, so I thought I'd post it anyway.)
I would consider calling your method something else. Nothing against numbers exactly, but what happens if the project slips it release date? You'll have a method called post2011 - when it should be called post2012 now. Consider calling it postProjNameImplentation instead maybe?
The use of number it is not bad itself, but usually they are not very common.
in the specific case, I don't think isSessionPost2011(int id) {} is a good name. but it is better isSessionPostYear(int id, int year) {} more extensible for future uses.
The fact it is a coding convention and the use of the verb "should" suggest you that digits are permitted but advised against in methods names. However in your example, why not generalizing the same code as?
session.isPostYear(int year);
We use 'em all the time, like the example you showed. Also for interface versions, like IConnection2 and IConnection3.
Eclipse doesn't complain that it's a nontraditional name, either. :)
But acceptable? That's kind-of up to you.
Don't ever forget - rules are made to be broken. The only absolute should be that there are no absolutes.
I don't believe there's a per se reason to avoid numbers in identifiers, although in the case you describe, I don't know that I'd use it. Rather, I'd name the method something like boolean isPolicyXyzApplicable(int id).
If this is a policy that's expected to change more over time, consider splitting policies out into different classes so you don't end up growing a long vine of if(isPolicyX) ... else if(isPolicyY) ... else if(isPolicyZ) ... in your methods. Once this is factored out, use an abstract or interface method Policy.isApplicableTo(transaction) and a collection of Policy objects to determine what to do.
As long as you have a reason for using numbers, then imho I think it's fine.
For your example, there might be 2 isSessionPost method, so how would you name them? isSessionPost and isSessionPost2? Not very clear to be honest.
Just remember that all names must be meaningful and you won't go wrong.
I think in your case it's OK to use it as a one-off marker, specifically if you expect that the method will only live for a short period of time and eventually be deprecated.
If I understand your use case, you need to bring in some legacy data into the new version of your application. If this is the case, then definitely add this method, mark it #deprecated and retire it when all your clients are updated.
On the other hand Ralph here has a valid point. Don't let this project to slip into 2012 :)
nothing is wrong
String int2string(int i)
User findUser4Id(long id)
void startHibern8();
wow! this website doesn't like these method names! I got captchaed!

Categories

Resources