As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In my introductory programming course, my teacher always uses the following naming convention when declaring instance variables in his code:
public class Snowman {
private Ellipse _top;
private Ellipse _middle;
private Ellipse _bottom;
public Snowman() {
_top = new Ellipse();
_top.setColor(Color.WHITE);
_top.setFrameColor(Color.BLACK);
_top.setFrameThickness(1);
_top.setSize(80, 80);
_middle = new Ellipse();
_middle.setColor(Color.WHITE);
_middle.setFrameColor(Color.BLACK);
_middle.setFrameThickness(1);
_middle.setSize(120, 120);
_bottom = new Ellipse();
_bottom.setColor(Color.WHITE);
_bottom.setFrameColor(Color.BLACK);
_bottom.setFrameThickness(1);
_bottom.setSize(160, 160);
}
}
In the course textbook, however, instance variables do not start with an underscore, but rather follow the same naming convention as that of primitive type variables (int revolutionsPerMinute). When I did an online search, I found several sources, including the online Javadoc, that cited the same convention as my textbook. As I could not reproduce the naming conventions my teacher follows, I am skeptical as to whether his convention is legitimate. Is the convention taught my teacher even existant, if not widely accepted?
Normally the standard convention in Java is camel case where you start the variable with lower case and using upper case for the first letter of every other word. For example:
int myVariable;
int mySecondVariable;
But note that these are conventions not rules. So anyone is free to use any convention, but it is recommended to use the standard convention to make the code readable for anyone.
Class names and Types
First caps: SomeClassName, URL (acronym)
Static, Instance Variables and Methods
Camel case: thisIsCamelCase.
Constants
All caps: A_CONSTANT
Packages
All lowercase: javax.swing.jfilechooser
I'd say convention is something that you follow while writing your code for the ease of the writing of the code. I don't think there is anything such as existent or non-existent convention. However, the classes you make may be used by other programmers too. So, they might have problems if they don't know the convention that you have followed. It is therefore suggested that you follow the naming convention followed by most java programmers:
int myFirstNumber;
ClassName objectName;
So, it is up to you to select the convention but I recommended following the standard that has been mentioned in the javadoc and your textbook.
no big deal with a leading underscore.
as long as it doesn't start with a capital letter - that will completely confuse java programmers.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
What is the naming convention of classes in java, for example should all classes be in upper case like MYCLASS.java ?
as some classes like com.sun.org.apache.bcel.internal.generic. ANEWARRAY. can be found in Sun's library as well
Note: I have read all naming convention from Oracle but I could not find anything which says we should name a class with All Uppercase.
Class Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world.
The Documentation states the following:
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).
Java has a very well described naming / coding convention.
You can look it up here http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html
Technically it doesn't matter how you name you classes as long as public classes are in a .java-source file with the same name as the class.
The quoted class com.sun.org.apache.bcel.internal.generic.ANEWARRAY looks to be from the deep innerworking of Java (internal.generic), i.e. not for developer use. As such its really outside of the naming convention. I can only speculate as to why its all in capitals, perhaps to emphasise this point that it shouldn't be used.
Usually the best practise is to use Upper CamelCase.anyway there will be no compilation issues with other conventions.see more details about conventions
After browsing through many links I came to know there is no java convention which suggests us to name a class in all uppercases. However we do so there will not be any error.
One appropriate reason is mentioned by CloudyMarble that we can use this convention if the abbreviation is more famous like HTML.
Also I would like to add some info about ANEWARRAY, this class comes under Apache license Source and Create new array of references.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm currently in the process of cleaning up a a large Java code base, and I was wondering what was the proper (standard?) structure/ordering of a Java class.
What I mean is:
Should public static final fields be first among the fields of a Class?
Where should a static initializer be?
Where should private static helper methods be?
Also, as a side question: is it a good idea to have large harcoded SQL queries for PrepareStatements in the code?
You should be more worried about naming convention, clear code documentation and overall the correctness of the program (i.e. no bugs), after this you can worry about the order of defining variables, methods etc
This is the code convention for Java
To answer (some) of your points:
static initializer usually appears in the begining of your classes, after the variables if it happen to come first.
private methods can go to the end of your class (before variables if they are at the end), but it is matter of preference, because usually the one who reads the code care more about the public methods that the class expose to the rest of the program
Having the SQL statement inside the program or stored externally (e.g. properties file) depends on how often they are changing; but as long as you are using PreparedStatement you should be OK.
Well, here you're gonna find Java code conventions: Java Code Conventions
I really don't like harcoded SQL statements. But, sometimes they are necessary. See if you can encapsulate that on a library (like hibernate or something), or if at least you can break it into minor sql codes.
Adding
I would also take a look at: How to Write Doc Comments for the Javadoc Tool to mantain your code well documented.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What of the following is used popularly or is the standard :
private List<String> names ;
OR
private List<String> listOfNames ;
OR
private List<String> namesList ;
Once upon a time we had Hungarian notation, because IDEs didn't provide intellisense and programmers were too dumb to realise that having a 30,000 line long block of code was unreadable*. Nowadays IDEs are friendly, programmers have started using small, neat classes, we have JavaDoc and things in genral are easier to read.
So, just name your variable for its usage. i.e. names. I'm no fan of pre/post-fixing variables as it often makes them harder to understand.
(*) i.e. Me, there's probably some deeply shameful code out there with my name on it.
Depends on the use case.
names
If this is the only "names" variable
namesList
If therr are other names collestions (e.g. namesSet) in your code.
private List<String> listOfNames
Is wrong; if you will be so specific you should write listOfStrings or
private List<Name> listOfNames
redefine your type (whatever Name is).
The conventional name will be namesList.
PS : If you use auto complete in Eclipse you'll see that.!
Regarding variable name, you can use anything.
My team says after reading variable name, one should understand what that variable will hold data BUT variable name should be as per Java naming convention.
In your case I would go with listOfNames, because it will say the variable is of type list and it has names.
Also read Java naming convention.
whatever is suitable for you and your team go with that.
IDEs are very smart they will take for everything else like what a given name stands for, type, permissions etc.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'd seen in old codes variables written with its datatype like:
double dblMyVar;
int intYourVar;
String strTheirVar;
But, nowadays, it seems to be old-fashioned. The advantages of this approach is that you can instantly see the type of a certain variable everywhere it is. But I do dislike long variable names. Whenever I can I name my variables in a single char, like:
private Product p = new Product();
There's a modern "good practice" or convention for naming variables? What do/does you/your company use?
When in doubt, consult the Java Language Specification (JLS). Here's the section regarding Naming Conventions.
// class member only if needed
private Product product;
// instantiates before using it
product = new Product();
Declaring the variable type in the name is pretty useless, as the IDE will show you its type on mouse-over. However, using single char names can be pretty confusing for other developers (specially if you have tons of variables) and goes against the self-documenting principle.
This notation is called "Hungarian" and was popularized by Microsoft, use it if it works for you: http://en.wikipedia.org/wiki/Hungarian_notation
It depends on the language.
About C#:
As it's a strongly typed language, adding the type of the variable as a prefix of the name of the variable (Hungarian notation) is not recommended anymore (too much verbosity and redundant information)
Starting variable names that are public with an upper case is a convention (for instance MyVariable): pascal case
Starting variable names that are private with a lower case (or an underscore then a lower case) is a convention too. Using underscore or not is a matter of personal preferences (for example: _myVariable or myVariable): camel case
Naming temporary variables (such as the variable used in a for loop) with a single letter (i, j, z...) is generally OK if the usage is limited to a small scope.
But it's all about personal preferences.
EDIT: General Naming Conventions on MSDN.
y_xName, y is l/m/p/s for local/member/parameter/static. x could be i for int, f for float, p for pointer, etc.. Perhaps sp for shared pointer.. Rarely anything for most types of object/references.. I prefer code to be self explanatory, hence no names like just "p" or "m_p". Say what it is. If it's a short snippet where it's really just a generic "product" of some sort I might name it l_Product for instance. I see no point in making tiny code, even if you're trying to stay withing 76(?) characters line width, breaking the line at a proper place then indenting can make it look alright and you still see from the verbose names what is actually happening.
Well that's just my take on it..
The only time you should be using "single letter variables" is within a very short piece of code, such as "foreach(var i in item)" or "using(var p = new Product())". Of course that comes down to your own preference, but there's a very nifty little addon for Visual Studio called StyleCop. It has a whole lot of styling checks for pretty much everything, and coupled with ReSharper it can do it real time and even fix things for you.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm reading some books about coding standard in Java.
I always loved beautiful and clean code.
But there are some things that bother me. For example, a method name should start with a lowercase word, and if it has a second word, it should be start with a uppercase character. But the standard for variables is the same thing. I think this is a little confusing.
So I'm asking you guys, what's your coding standard in Java?
Like:
How do you name objects, methods, classes, etc.
If you have more than one object from same class, how do you name the second one?
If you have one object in the argument of a method and you have another object from the same class inside this method, how you do name both of them?
What is the best trade-off for performance/code beauty, a lot of small methods, or some longer methods?
Feel free to say something more. =)
Mostly following the Java code convention.
I try to not make it matter what kind of class an object is. If I for instance have five different strings, the name of each variable should describe what information/content the variable represents, and not that is is a string.
I find it often silly to try coming up with variations of a variable just because it exists both as a method argument and a class variable. I mostly use the same name with this syntax this.theVariable = theVariable
A method should be as short as possible: as few lines as possible, and as few nested levels as possible (i.e. max one if-statement, and not ifs inside ifs etc.)
Robert Martin's Clean Code is highly recommended!
Just to address one specific point, because it's one I commonly see people doing horrific things with:
If you have more than one object from same class, how do you name the second one?
By their purpose, surely. If you have two different objects of the same class, you must be using them for different purposes, so name it after that purpose. I think all of these examples would be pretty self-explanatory to most readers:
public void copyAddresses(Customer source, Customer destination) {
public void sendMessage(Mailbox sender, Mailbox recipient) {
public void changeContactCompany(User contact, Company from, Company to) {
public void eatWatermelon(Bowl servingBowl, Bowl bowlForSeedSpitting) {
or whatever... you get the idea.
You should start with the official Java Code Conventions.
They will explain why code conventions are needed, different conventions and, what your question seems to be about, naming conventions. They add various examples too.
What is the best trade-off for
performance/code beauty, a lot of
small methods, or some longer methods?
"Premature optimization is the root of all evil" - Donald Knuth
Remember:
Make it work.
Make it right.
Make it fast.
You should only worry about performance if it is warranted; if the current code is too slow to meet requirements.
In that case you should find the 'hot-spots' and optimize those. Check if performance is good enough. If not, repeat.
Well since most of these are easily googled I will add my own standard Java naming practices:
I usually suffix the name of classes of what they extend or implement.
In other words Spring MVC controllers are suffixed with "Controller". This makes it easy in Eclipse to do a Crtl-Shift-R *Controller.
Second if I find I need to aggregate a whole bunch of static methods in a class I usually suffix that class with "Utils". I got this from Apache Commons and has just stuck.
Finally derived methods that do special expensive stuff and are transient I avoid calling them getXXX. The reason is to avoid problems with serializers.
Look here at the official guide