Standard for programming 'beautiful' code in Java? [closed] - java

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

Related

Splitting Declaration and Assignment = Good Practice? [closed]

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.
Being an avid user of NetBeans, I keep getting suggestions to split my variable declarations and assignments when I introduce a new variable. As a super quick example off the top of my head, let's take this Java line:
String someInput = JOptionPane.showInputDialog(null, "- Enter something: ");
versus:
String someInput;
someInput = JOptionPane.showInputDialog(null, "- Enter something: ");
NetBeans seems to prefer the latter (I wouldn't know about other IDEs, though). While it clearly works both ways, which would be considered 'good practice', if at all? Or s it purely a matter of personal preference?
(Obviously splitting the two means an extra line that you could've just combined into one, but that's beside the point.)
There's no reason to split the declaration and the assignment if you're just going to have them on consecutive lines. I'd only split them if the assignment were conditional, or if it needed to go in a separate code block (like a try/catch, or if the assignment goes in a constructor, etc.).
A common pattern that traces back to early statically typed programming is to declare all the variables you need at the top of the block they need to be scoped in, and then assign to those values subsequently.
With that said, as long as you're able to clearly communicate the intent of your code to the people you work on it with, or yourself in a year's time, it shouldn't really matter.
Let us change our traditional attitude to the construction of programs: Instead of imagining that our
main task is to instruct a computer what to do, let us
concentrate rather on explaining to human beings what
we want a computer to do. -- Donald Knuth
This was an option added to NetBeans somewhere between 7.0 and 7.3. If you don't like this hint it can be changed by unchecking:
Tools > Options > Editor > Hints > Suggestions > Split Declaration
Netbeans suggests this as it can speed up coding, for example consider this assignment
final String myString = "somevalue"
You then decide that actually the value depends on some boolean
final String myString;
if(something) {
myString = "somevalue"
} else {
myString = "someothervalue"
}
To convert one from to the other you can use the code hint to spilt declaration and assignment and the if...else template to generate the code in very few steps.
In general if you are assigning unconditionally then there is not reason to split declaration and assignment.
I don't think it's a big deal. Pick a style you like, and stick to it throughout (if you're in a team, it helps if everyone is laying out their code similarly).
I personally prefer to initialize my variables right at the point of declaration. For that reason, I would prefer the former over the latter.
Code Complete, which is well regarded by most of the programming community, suggests in its page 241 that as a matter of defensive programming you can either initialize each variable as it's declared (your first option) or initialize it close to where it is first used (your second option).
Nevertheless, the book suggests that the second option is better because if you use the first option, your variable may have changed between its declaration and its usage.
In your case, the difference between declaration and usage in the second case is a single line. Hence, the book's concerns do not apply. Nevertheless, its concerns are legitimate and this may be the reason Netbeans designers included this tip (even though they overused it).

Best practices with class visibility [closed]

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.
Is it best practice to have all the classes public in a Java project? I have noticed that in all Java projects I have worked with, there have only been public classes.
It isn't a guideline, no.
The information hiding principle tells us to only exposed what is required, and nothing more, to minimize coupling.
So, for example, if a class lets you handle logic in a separate class easier, and is only used by that class, there's no reason to have it public, nor should you make it public.
The simple answer to your question is "no!"
The slightly more complicated one is that you should only make a class public if it needs to be used by other classes outside it's own package. But if, like me, you break you project up into many packages for readability, then then if will often be the case that your classes will need to be public to be usable.
While your question is simple to ask, it is far from simple in its nature. Much will depend upon the kind of code your writing. It you're writing a library then use externally is probably high on your agenda. In an application less so.
I have found that I prefer the public approach. I try and design for reuse because it keeps my options open, causes me to think more carefully about my implementation because of the reuse issues, and that leads to better code. But it really is horses for courses, you are the biggest variable in this equation.
It depends, For top level class's, If you want other class's in a different package to view your class you should mark it public. If you only want class's in the same package to view you class mark it default(no-modifier).
So, your question is really, should all top level classes be public? I think it boils down to the usage of the package access that you do in your project. This question was relevant to that, some time ago.
Usually most classes are indeed public but there are cases when you might want to use default or private scope as well.
A class using the default scope is only accessible to other classes in the same package. In case of helper classes for example it's often a good practice to limit their use this way as your code becomes more encapsulated. The private scope can often be used for inner classes for the same reason.
No it is not. There are lot of classes with other access specifiers or even anonymous. For an example, you can write private or anonymous classes that can be registered to listeners like
'ActionListener' and 'ItemListener'. Just like that, for various purposes, we do write lot of classes with no public specifier. It really helps to separate your work into pieces.
However, in Java, normally every source file contains a public class. That is because if your source file's name is 'Reader.java', you cannot have a private or other access specifier for the class 'Reader' inside that source file. It must be public or default. Apart from that, no other class can have the access specifier 'public' instead of 'Reader' class.
Other thing is, private, protected and other types (except default) of classes cannot be written in a source file as "Independent classes". For an example, following is an error
Check.java
private class Check
{
}
It definitely is not best practice. You are seeing it because most programmers don't know that a top-level class doesn't have to be public.
Ideally, a package isn't just a way to organize classes into groups. There is no minimum or maximum number of classes that belong in a single package; rather, subpackages should be created only when there is a need for package-level classes and/or members. Java APIs do this a lot, and since the javadoc distributed from Sun/Oracle is generated for protected-level classes and members, some packages may appear to be sparse, even to the point of appearing nonsensically so.
For instance, the javax.swing.colorchooser package appears to have only four classes, but it actually has 17 (actual number may vary depending on the version of Java). Four are public; the rest are only for use with JColorChooser internals.
I've found that an inner class that is becoming too big to be easily maintained as an inner class is usually a good candidate for being a non-public top-level class.

Questions about Java code styles [closed]

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.
So I have seen a lot of different coding styles, but I'm only going to talk about two big ones. I use a style where I just name everything like their class name when used in a general sense, like this:
String str = "This is some text";
But over at Java Practices, I see a style where they will put an 'I' in front of Interfaces class names, or they put 'f' or 'a' in front of object names. Take this snippet from "Don't subclass JDialog or JFrame"':
/**
Constructor.
<P>Called when adding a new {#link Movie}.
*/
MovieView(JFrame aParent) {
fEdit = Edit.ADD;
buildGui(aParent, "Add Movie");
fStandardDialog.display();
}
Why do programmers code in this style? Do a lot of people use it? And also, do professional programmers use this style?
Thanks in advance :)
This my personal opinion.
I prefer not to use prefixes on interface (or anything else for that matter). I just prefer to call it what it is. Interfaces are meant to represent an object (or part of it) without making any implication towards it's actual implementation.
Say you have a Car interface. And AudiA4 could be an implementation of that car. If you just bought a new Audi A4, you say, "I bought a new AudiA4" to those you think care about the kind of car you bought. To others, you can say "I bought a new Car". Certainly, you never say, I bought a new IAudiA4 or a new ICar.
The JFrame naming came about because it's a Swing Frame and Swing came after AWT (the original Java windowing toolkit, which already had a Frame class). Since both AWT and Swing where available at the same time, they used the 'J' prefix to demarcate the toolkits (note that JFrame extends Frame, btw). They could have called it SwingFrame but the 'J' prefix was apparently a good choice to represent the Swing package. So basically this prefix is just a naming choice, not a convention similar to the 'I' for interfance (or Impl suffix for implementations you see sometimes as well)
My point is you always have to name your classes and interface according to exactly what they represent. No more, no less. No point having a CarImpl class. Who cares that it's an implementation. Which implementation is it? Why does it need its own class? What more do I get when I use a CarImpl? What happens when I make a second implementation, I call it CarImpl2? All this is very constraining and doesn't bring much value.
Call it what it is. That's the only rule I'd set forth.
All this being said, the Eclipse project, amongst many others, does indeed use the I-for interface notation (WIKI). But it's their choice. I've seen professionals use it as well. I don't like it, but generally speaking, I respect the team's naming convention.
There is a book about such things - Code Complete by Steve McConnell
I might be wrong but the only universal convention I've seen when naming Java variables is using Camel-Case notation, that's regarding the format of the name.
As for the name itself, I've always found useful to name the variables according to what they actually are. In your String example, although you mention this would be in a general purpose variable, I would still give it a more meaningful name, like:
String message = "This is some text";
Or:
String msg = "This is some text";
Some of the Java libraries I've seen source code from tend to be quite verbose when naming variables, others just use single letter names when the variable is used in a reduced context:
public Rectangle setLocation(Point p) {
return setLocation(p.x(), p.y());
}
I think the main goal when naming variables (or anything else for that matter) is always to communicate in the best way possible the intent of what you were trying to do.
Code styles help make it easier for developers to read and understand each others code. Java conventions prescribe the use of short and descriptive identifiers, but unfortunately short and descriptive cannot always be achieved together so you may have to compromise shortness for clarity hence: atmosPres - still clear but short, atmosphericPressure - this can't be mistaken, atm - because everyone just knows ATM, right?, ap - WTF?
I first encountered the practice of prefixing variable names with a three letter type identifier while developing programs in C# - it helps the reader know what data type is contained in a variable without having to look for its declaration (due to short memory or maybe laziness?). Arrays are also prefixed with I e.g IList to distinguish them from other data types (and for what purpose, I just dunno).
For me, the worst code conventions are in C++ (if indeed there are any at all) - there's a mix of case types for data types and variables, conflicting method and function naming styles and endless cryptic abbreviation which all make it hard for non-regular C++ coders to read and understand C++ code.
What you're describing is sometimes referred to as "Hungarian notation", though it's not "Hungarian" in the truest sense of the term.
Basically, the idea is to differentiate between different classes of variables -- instance variables, local variables, parameters, et al. This serves two basic purposes:
It helps avoid name collisions, where, say, there might naturally (using "descriptive" variable naming) be an instance variable ralphsLeftFoot and a local variable ralphsLeftFoot. Using a prefix allows the two to co-exist, and, especially in languages where the local might (without warning message) "hide" the instance variable, prevents unintended changes in semantics from such collisions.
It makes the scope of variables obvious, so that, during maintenance, one does not accidentally assume that a local variable has instance scope or vice-versa.
Is this approach worthwhile? Many developers use a subset of the scheme, apparently to good effect. For instance, many Objective-C developers will name the instance variable behind a "property" with a leading "_" character, to clearly differentiate between the two and to avoid accidentally using the instance variable when the property was intended.
Likewise, many developers in a number of languages will prefix instance variables with a letter (often "m") to differentiate them from "normal" local/parameter variables.
What's probably most important is to pick a style that you (and your team) likes and stick with it. If the team likes the prefixes then use the prefixes. If the team prefers something else, stick with that. Of course, changing preferences, when a better choice is "revealed" to you, is OK, but don't switch back and forth willy-nilly.
So I have seen a lot of different coding styles, but I'm only going to
talk about two big ones. I use a style where I just name everything
like their class name when used in a general sense, like this:
String str = "This is some text";
That is awful. Imagine if someone were reading your code, trying to understand what it was doing, and they came across a variable named str. It doesn't convey any meaning to the person who has to read this code as to your intentions.
Conventions are used by and for people to improve readability, and thus the overall quality of software. Without a convention, any project that has more than one developer will suffer from varying styles that will only hurt the readability of the code. If you want to know what professionals do, look around on the internet for various conventions.

Using getter / setter inside a class - good or bad practice? [closed]

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.
Using a getter/setter in the internal code of a class instead of accessing the instance variable directly, is it good or bad practice? At least for setters one could add additional code validating the value, but for the getters it's just overhead? How intelligent is the Java compiler, if my getters/setters just set/get the value directly, will Java optimize my code and replace the getters/setters by direct access to the instance variables, so there's no method calling overhead?
It is more common to access the field directly. The value of a setFieldName method is more obvious for programmers using your code in other classes. With the implementation details hidden, they might not realize what ranges of values are acceptable, so keeping fields private and forcing other developers to go through a setter makes sense. But inside your own class, the case for using a setter is much weaker. If you look at the source for the java API you'll find that getter / setter methods are generally not used within a class.
There is no need to do that inside a class, unless want to perform additional operations in those getters / setters.
The access to the class members can be direct to the class internally, as:
The reason for hiding is mainly to hide the implementation (and there's no need to hide the implementation from the class itself)
The getters and setters access the members directly, so to call them just to avoid access the members directly is somewhat, umm... redundant.
Regarding performance - I honestly think that in most cases, you shouldn't think about it, you should decide whether to call a method or access directly in terms of readability, scalability and maintenance, not in terms of whether it will take another nano second or not. This approach pays off in the long run. There are places for optimizations, and you should be efficient, but keeping your code clear and maintainable is much more important once the code base is over 20 lines.
Accessing directly is a good thing. However, no one can say getter/setter access is bad, inside the same class. If you are developing a Java bean, you will definitely understand what I am saying. Think you are trying to get the user input of a JTextField as a String. In this case, the getter methods will allow you to do lot of things including String truncating, trim, uppercase, lowercase, etc. If you are trying to do this all just by accessing the direct variable (eg: String s = textField.getText()), you will find it quite difficult to do it. So, what I think is, the good or bad depends on the situation and what you are developing

What taxonomy for variables do you use? [closed]

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.

Categories