The Java language gives you all the room you need to write code that would be very difficult for others to understand. Java also permits you to write code that is very easy to understand. Most development teams would prefer the latter.
A style guide provides provides a map so that the code generated by a group of programmers will be consistent and, therefore, easier to read and maintain. Many people do not care for the style guide offered by Sun. This document is one alternative.
This document covers most areas where there could be confusion or difference of opinion. Areas that have never been a problem in our experience are undocumented.
if
,
while
,
for
,
switch
, and
catch
must be followed by a space.
class Order
{
// fields
// constructors
// methods
}
All identifiers use letters ('A' through 'Z' and 'a' through 'z') and numbers ('0' through '9') only. No underscores, dollar signs or non-ascii characters.
All class and interface identifiers will use mixed case. The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case. (examples)
Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided. (examples)
do..while
. (
examples and reasoning)
return
in the middle of a method. (
reasoning)
continue
. (
reasoning)
break
other than in a switch statement. (
reasoning)
Use a separate line for an increment or decrement. (examples and reasoning)
Never use pre-increment or pre-decrement (examples and reasoning)
"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."
--- Martin Fowler, Refactoring: Improving the Design of Existing Code
Rather than trying to document how you perform a complex algorithm, try to make the algorithm easier to read by introducing more identifiers. This helps in the future in case the algorithm changes but someone forgets to change the documentation. (examples and reasoning)
原文链接在 http://www.javaranch.com/style.jsp