Java Code Style
Something to annoy everybody here - but in general consistency and readability is the aim. We're largely following the Sun recommendations but with some tweaks partially due to history and partially due to preference. Submitting code that conforms to the style set out here makes it much easier for developers to compare it to existing code and to see what has changed.
Indenting
2 characters - no tabs. If you use eclipse there's a plugin to convert all tabs to spaces. Look for "AnyEdit? tools" on Google.
Why 2 spaces? It's been that way a long time, eclipse handles it and changing all the source is pointless.
Blank lines
1 blank line is enough.
Layout
it's
if (expr) {
statement;
} else {
statement;
}
No spaces before ')' no spaces after '('.
Do not use
if (expr) statement else statement;
or any other variant. It's less clear than the bracketed form. Also see the notes below.
Width
Try to keep it within 72 to 80 - anybody remember why 72 and 80? Some of us are old enough. Align parameters under each other etc etc.
Imports
Within groups sort alphabetically. Ordered as follows
- org.bedework
- edu
- net.fortuna (ical support)
- java
- javax
- org
- com
Remove (or comment out) all unused imports.
Method and field ordering
Keep the class ordered:
- Fields
- Constructors
- public
- protected
- private
Unused code
Try to keep it to a minimum. Eclipse will report all unused code - the ideal is zero messages. The practical is probably about 15-20.
conditional expression a ? b : c
Please don't. They are even frowned on by the certification book.
Setters and getters
The conventions is set before get - unfortunate that eclipse does it the other way but we already have a lot. Setters and getters are just about completely self documenting though the comment could say what the property is if it's not obvious (it usually is). Name the set parameter "val" and we have nice concise code:
/** Set the description for this thing
*
* @param val String description
*/
public void setDescription(String val) {
description = val;
}
/** Get the description for this thing
*
* @param val String description
*/
public String getDescription() {
return description;
}
Use the Setters and getters
Not so much a code style thing but very important. In the hibernate world (and many others like it) byte-code is injected into the classes to set property values. If you refer to the property directly other than in the getter or setter you can avoid triggering the fetch so you might get a null value instead of the actual db value.
Exception bad, Throwable good
There are whole classes of exception which throw Throwable rather then Exception. Catch these and wrap them othewise we can cause problems in the server environment, especially in the j2ee world.
Many exception classes bad - few good
This refers to the throws clause of methods. Listing large numbers of exceptions does not help.
It is possible to define an exception class for every type of exception that might occcur: it doesn't help much in the end. One exception per project is enough. The usual response to an exception is to report it and give up. Recovery is hard to impossible. Related to all of this is the j2ee behavior of terminating any session that throws an undeclared exception. At the session interface we have to declare all exception classes thrown. The fewer the better.
Subclasses of a global package exception class are not included in this. They are useful for identifying which particular exception was caught - for example access denied exceptions.
=== Do NOT swallow exceptions ===Java annoyance: final parameters
August 26, 2008
First, the summary:
Q: What does it mean when a method I’m calling declares that its parameters are final? A: To you, nothing. It’s a safety feature for the author of the method.
Q: OK, so when should I declare method parameters as final? A: Absolutely always.
Q: Isn’t that just annoying busywork? A: Pretty much so, yes. You must be new to Java.
And now, the lengthy discussion.
Way back in the days when the closest thing to a decent programming language available to me was C or Pascal, I disliked functions with side effects. At the time they mostly seemed to me to be a nasty hack to get around the fact that there was no easy syntax for returning multiple values.
Today, I’m even less of a functional programmer than I was in college; but I still see functions with side effects on their arguments as evil. Sometimes a necessary evil for performance reasons, but evil nevertheless. (Obviously side effects on an object by its own methods aren’t anywhere near as big of a problem, though I like that Ruby distinguishes them from side-effect-free methods by a special naming convention.)
So my deeply ingrained habit is to treat function/method parameters as unmodifiable, whatever the programming language. I had actually forgotten that this was a habit until I started running PMD on my Java code, and promptly had it warn me that every single method parameter ought to be declared final. This in turn made me think about Java’s method call semantics, and how badly chosen and useless the word "final" is on method parameters.
In C and C++, the const keyword is used all the time when library functions accept string parameters, and provides the caller with a guarantee that the function will not modify the string. For example:
int strcmp(const char *s1, const char *s2);
You might naively expect that in Java, final performs a similar function–but it doesn’t really.
First off, in Java all Strings are immutable. So whether arguments are final or not, your strings will never be modified by being passed to a method.
Secondly, in Java all objects are passed as a value consisting of a pointer to the object. The Java Thing a is really like C++ Thing *a, and Java’s a.method() is really C++’s a->method(), not a.method().
To look at it the other way, if you could have an actual object in a variable x, Java’s foo(x) would really be doing a C++ foo(&x)–but in Java, you never get to touch the actual object x.
It seems that the designers of Java wanted to make sure nobody confused their object pointers with the evil manipulable pointers of C and C++, so they decided to call them references instead. So Java books usually say that objects are stored as references, leading people to think that objects are passed by reference. They’re not, they’re passed by value, it’s just that the value is a pointer. If you’re confused again, try going back a couple of paragraphs.
Anyhow, the upshot of pass-by-value with objects represented by pointer values, is that as a caller of a Java method, the presence or absence of final on parameters tells you absolutely nothing. Even if the parameters are all final, the method can still modify the value of any objects you pass in, unless the objects themselves are special immutable ones like the String class. Contrariwise, even if the parameters aren’t final, the method can’t make your variables end up pointing at a different object.
This is undoubtedly why JavaDoc ignores final on parameters when generating documentation.
What about the value to the author of the method? Well, reassigning parameters is pretty much universally viewed as a bad thing to do, and Eclipse will warn you about it.
If you’re not convinced it’s unwise, consider the case where you have a constructor with a parameter ‘name’ that gets set as the initial value of a field, also called ‘name’. If parameters are final, there’s no way to accidentally modify the parameter when you think you’re modifying the field. Yes, Eclipse warns about parameters masking fields too, but still… more safety is good if the cost is low.
So let’s consider what would happen if we made all parameters final by default.
There may be a rare occasion where you genuinely need to change values passed in to a method before performing some computation. Since every object in Java is manipulated as a pointer, it’s computationally trivial to introduce a temporary variable that’s a copy of the parameter, and then either change it to point to a different object or not. So instead of
void foo(Object x) {if (x == null) { x = SOME_DEFAULT; }...}
you’d have to do
void foo(Object x) {Object c = x;if (c == null) { c = SOME_DEFAULT; }}
No big problem.
How about performance? Well, it turns out that the final-ness of parameters isn’t part of the method signature. I also checked, and the compiled class files are byte-identical whether your parameters are final or not. So, no performance benefit either way.
Finally, no pun intended, the use of final on parameters is required when using inner (nested) classes for listeners or iteration. This crops up all the time in Swing programming, and a Google search shows that it’s a common cause of intense confusion.
So I don’t see any value to making the final-ness of parameters a matter of choice for method authors either. They should all be final, always. You won’t see any significant performance change, but you’ll get a bit more safety, and you’ll be a bit less likely to encounter a weird error message when attempting to use listeners and iterators.
So the actual word final on method parameters is just noise, providing no benefit to API users, programmers with good coding habits, or anyone using a tool like Eclipse that warns about reassigning parameter variables. The language should have made final parameters at least the default, and ideally the only option. It annoys me that I end up with my method declarations cluttered with final, final, final. Always report in some way - do NOT continue - rethrow the (wrapped) exception or recover. If you cannot figure out what to do then FAIL and let somebody else figure it out.
final on parameters
Why? The text from http://lpar.ath0.com/2008/08/26/java-annoyance-final-parameters is copied into Why final? in case it disappears.
This is a new one - final being added throughout.
Some notes from enerjy.com
Omitting braces: Not just a matter of style
According to our analysis of more than 100 Java projects, one of the most violated rules is 'missing braces in If statement.' Although often considered to be merely a stylistic preference, we found that omitting braces is actually a good indicator of probable buggy code.
For example, when developers need to add to existing code and forget to add braces where the original statement only contained a single line of executable code, e.g.
//original code if (condition) doSomething(); //new code if (condition) doSomething(); doSomethingElse();
The intent of ‘doSomethingElse()’ is only meant to execute if ‘condition’ is true. However, omitting the braces in the If statement means doSomethingElse() will execute regardless of the value of ‘condition,’ hence the bug.
