Mitarbeiter
The created code should not only be easily readable for machines, but especially for humans.
Following the Style Guide of Sun here we introduce the most important code conventions. These have to be obeyed in the programming language 2 lab course, so the code can be easily understood not only by its creators. These conventions may be devised differently in companies, but neither version can be regarded as superior.
1 – Formatting
1.1 - Indentation
For indentation 4 spaces should be used. Tabs must not be used.
Reason: Code that has been indented through spaces will be displayed the same in all editors. If indentation through tabs and spaces are mixed or if the code is displayed in an editor with deviating tab length, the readability is diminished.
Closing braces are always in the same column as the corresponding construct.
void example() {
while (count > 0) {
System.out.println();
count--;
}
}
All if-, while- and for-constructs have to use braces, even if they only relate to a single statement.
Reason: If lines have to be added or removed, the bracketing does not have to be changed on any account. The code will always look the same.
if (foo == bar) System.out.println("equal"); // only in exceptional cases
if (foo == bar)
System.out.println("equal"); // not good
if (foo == bar) {
System.out.println("equal");
} // PREFERRED
if (foo == bar)
{
System.out.println("equal");
} // might be used as well
1.2 - Spaces
Between method name and successive parenthesis and between array identifier and the indexing square bracket, there are no spaces.
Reason: While bracketing already separates corresponding variable- and method names, highlighting of an operator or keyword is supported by spaces.
foo (i, j); // Bad
foo(i, j); // GOOD!
args [0]; // Bad
args[0]; // GOOD!
Binary operators have a space on both sides.
a=b+c; // Bad
a = b+c; // Bad
a=b + c; // Bad
a = b + c; // GOOD!
z = 2*x + 3*y; // Bad
z = 2 * x + 3 * y; // GOOD!
z = (2 * x) + (3 * y); // GOOD!
Unary operators are right next to their operands.
count ++; // Bad
count++; // GOOD!
A comma or a semicolon is followed by a space.
for (int i = 0;i < 10;i++) // Bad
for (int i = 0; i < 10; i++) // GOOD!
getCellValue(x,y); // Bad
getCellValue(x, y); // GOOD!
The keywords if, while, for, switch, and catch are followed by a space.
if(hungry) // Bad
if (hungry) // GOOD!
while(pancakes < 7) // Bad
while (pancakes < 7) // GOOD!
for(int i = 0; i < 10; i++) // Bad
for (int i = 0; i < 10; i++) // GOOD!
1.3 - Maximum line length
Lines are not allowed to be longer than 100 characters.
Reason: If you have to scroll to read a line, or if the line is cut off when printed, it is cumbersome to grasp that line.
1.4 - Wrapping Lines
When an expression is too long to fit on a single line, break is according to the following rules:
- Break after a comma.
- Break before a binary operator.
- Prefer higher-level breaks to lower-level breaks.
- Align the new line with the beginning of the expression at the same level on the previous line.
- If the above rules lead to illegible code, indent 8 spaces instead.
- After breaks in if statements, you should always indent 8 spaces to distinguish it from the body (4 space indentation).
Example for a breaking method call:
someMethod(longExpression1, longExpression2,
longExpression3, longExpression4, longExpression5);
var = someMethod1(longExpression1,
someMethod2(longExpression2,
longExpression3));
Example of breaking an arithmetic expression (The break at a higher level is preferred.):
longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6; // PREFER
longName1 = longName2 * (longName3 + longName4
- longName5) + 4 * longname6; // AVOID
Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if used conventional indentation, so instead it indents only 8 spaces.
//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg,
String yetAnotherArg, Object andStillAnother)
{ ... }
//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static void incredibleLongMethodName(int anArg,
Object anotherArg, String yetAnotherArg,
Object andStillAnother)
{ ... }
After breaks in if statements, you should always indent 8 spaces to distinguish it from the body (4 space indentation).
//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) { // Bad
doSomethingAboutIt(); // easy to miss
}
//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) { // GOOD!
doSomethingAboutIt();
}
1.5 - Parentheses in Statements
When in doubt about the evaluation order in statements, use parentheses
2 – Identifiers
Identifiers solely consist of upper and lower case characters and digits ('A'..'Z', 'a'..'z', '0'..'9').
Use CamelCase to connect multiple words (each word begins with a capital letter).
2.1 - Classes and Interfaces
Class and Interface names should be capitalized. The names for classes should be nouns, for interfaces adjectives. Included abbreviations consist solely of upper case characters.
Customer
Car
TargetURL
URLTarget
2.2 - Methods and Variables
The first letter of the name is lowercase. If a name starts with an abbreviation, it should be lowercase. A method name should begin with a verb, after which may follow nouns. Even if the method does not have any parameters, the parentheses have to be listed to differentiate a method call from a variable use.
getCustomerFirstName() // method name
showTargetURL()
urlTarget // variable name
2.3 - Packages
Names for packages should consist of a single word in lowercase. The length should be less than 8 characters.
2.4 - Constants
Class constants should be all uppercase with words separated by underscores.
static final int V_A_TAX = 19.0;
3 – Coding
3.1 – Constructs to be avoided
return Multiple return statements should be avoided. It is not permitted to exit loops or compound statements in the middle through a return. Such a routine is hard to grasp, as the condition under which the loop/routine terminates is not clear.
continue may not be used. Ever.
break must only be used in a switch statement.
Reason: The flow control is easier to understand that way. The method can easily be split into multiple smaller methods.
3.2 - Declaration and Initialization
Variables should only be declared at the beginning of blocks (a block is any code surrounded by curly braces). The only exception to the rules is indexes for for loops which can be declared in the for statement.
Reason: Code is more portable that way. After exiting a block, the appendant declared variables will be released.
void doFoo(){
int foo = 0;
if (MY_CONST == 0) {
int bar = foo;
...
}
}
Initialize variables when they are declared, except when the initial value depends on some computing occurring first.
Reason: That way initialization are carried out wisely and it’s harder to forget to do them.
int firstWide = DEFAULT_FIRST; // not necessary yet
int secondWide = DEFAULT_SECOND;
firstWide = doFoo(firstWide, secondWide);
doBar(firstWide, secondWide);
int totalWide = firstWide + secondWide; // declaration too late
int totalWide; // GOOD!
int secondWide = DEFAULT_SECOND;
int firstWide = doFoo(DEFAULT_FIRST, secondWide);
doBar(firstWide, secondWide);
totalWide = firstWide + secondWide;
3.3 - Access
Make all instance and class variables private. The only exceptions to the rule are selected constants.
4 – Self-explanatory code
- "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
Better than extensive comments that are likely to get out of date the code evolves, are meaningful identifier and useful summaries.