It is important to have a reasonable indentation style and to use it consistently in your assignments!
For the conventions to work, every person writing software must conform to the code conventions. Everyone.
If you already have programming experience, in Java or another language, you may be initially uncomfortable at giving up some fond habits. However, it is a sign of professionalism to set aside personal preferences in minor matters and to compromise for the benefit of your group.
Adapted with permission from JAVA CODE CONVENTIONS. Copyright 1995-1999 Sun Microsysytems, Inc. All rights reserved. The Java Code Conventions Web site is at: http://java.sun.com/docs/codeconv/
If I try to formulate a simple "rule" for how to indent it would be (perhaps I have forgotten some more special cases)
A '{' always cause a new line and indentation on the next line e.g.
if (...) { xxxxxxxA '}' always cause a new line, reindentation and usually one more new line e.g.
if (...) { xxxxx } nnnnnnSome exceptions exist, for example before else if
if (...) { xxxxx } else if (...) { xxxxx }
Avoid lines longer than 80-100 characters, since they're not handled well by many terminals and tools and long lines are hard to read.
The first style below is usually better because it saves space. If you desperately want more space use the second style. (The only difference is the placement of the starting block parenthesis({). Sun recomends the first alternative.
class Syntax { public static void main( String args[] ) { int aVariable = 5; // usually declare all variables at top if ( aVariable < 6 ) { // always use a block ({}) System.out.println( "True" ) ; } else { System.out.println( "False" ) ; } } } // ************* second, not so god, style class Syntax { public static void main( String args[] ) { int aVariable = 5; if ( aVariable < 6 ) { System.out.println( "True" ) ; } else { System.out.println( "False" ) ; } } }
if (door.isOpen()) { if (resident.isVisible()) { resident.greet("Hello!"); } } else { door.bell.ring(); }
This is one reason for blockstatements:
As in C and C++, the if
statement of the Java programming language suffers from the
so-called "dangling else
problem," illustrated by this misleadingly formatted example:
// DANGEROUS EXAMPLE if (door.isOpen()) if (resident.isVisible()) resident.greet("Hello!"); else door.bell.ring(); // A "dangling else"The problem is that both the outer
if
statement and the inner if
statement might conceivably own the else
clause. In this example, one might surmise that the programmer intended the else
clause to belong to the outer if
statement. The Java programming language, like C and C++ and many programming languages before them, arbitrarily decree that an else
clause belongs to the innermost if
to which it might possibly belong.
Another reason is that a very common bug is to add another statement witout adding a block (if there are no block to start with).
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3));
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 it used conventional indentation, so instead it indents only 8 spaces.
Line wrapping for//CONVENTIONAL INDENTATION someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS private static synchronized horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... }
if
statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:
//DON'T USE THIS INDENTATION if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { //BAD WRAPS doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS } //USE THIS INDENTATION INSTEAD if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } //OR USE THIS if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); }
argv++; // Correct argc--; // Correct argv++; argc--; // AVOID!
Compound statements are statements that contain lists of statements enclosed in braces "{ statements }
". See the following sections for examples.
if-else
or for
statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
if (boolean expression) {
statements } | Conditional (Use block statements even if there are only one statement) |
if (boolean expression1) {
statements } else if (boolean expression2) { statements } else { statements } | Conditional with else |
switch (integer expression) {
case value : statements break; // exit the switch case value1 : /* falls through */ case value2 : statements break; // exit the switch ... default : statement break; // exit the switch } | switch (integer expression has to be of type int or char) Each case selects one possible value. This one selects two. Don't forget "break" |
Every time a case falls through (ie. doesn't include a break
statement), add a comment where the break
statement would normally be. This is shown in the preceding code example with the /* falls through */
comment.
Every switch
statement should include a default case. The break
in the default case is redundant, but it prevents a fall-through error if later another case
is added.
Example: if statement and it's indentation (always use a block { }):
if (a<6) { System.out.println("a är mindre"); } else if (a==6) { System.out.println("a är lika med"); } else { System.out.println("a är större"); }Specifically observe that one normally never writes
if (bool-expr) { return true; } else { return false; }The correct way of writing this is
return bool-expr;And you never compare a boolean expression to a boolean litteral as in (
if (a==true) ...
).
for (initializer; bool-expr; change) {
statements } |
for loop Used when we know the number of turns. All of initializer, test and change are optional initializer and change may be several comma separated statements. initializer is executed once, the body is executed as long as boolean expression is true and change is executed after each iteration of the loop. |
while (boolean expression) {
statements } | while loop, executes 0 or more times |
do {
statements } while (boolean expression); | do loop, executes 1 or more times |
Example, loop statemenst and their indentation (always use a block { }):
for (int counter=1; counter<10; counter=counter+1) { sum=sum+counter; } counter=1; while (counter<10) { sum=sum+1; counter=counter+1; }Simple rules:
for
-statement should be used to
model the concept of "doing something for every member of set of fixed size" and nothing else.
Most of the time the set is a range of integers and we would like to
do something with every number in the range (either in order or in reversed order).
In any other case when you need a loop, use the
while
or do
-statement.
A few reasons for this are
for
-statement is constructed for the above
purpose, if you use it in other ways the for
-statement
would loose its documenting value. Even worse, if not careful the
reader may make false assumptions of the semantics of your code based
on the standard use of for
-statements.
for
-statement, since it is made up of so many
parts, makes it easy to write code that is hard to read and understand.
// do something with every integer i in [l..u] in order for(int i = l; i<=u; i++) { ... // do something with i } // do something with every integer i in [l..u] in reversed order for(int i = u; i>=l; i--) { ... // do something with i }Sometimes one would like to step more than one element in the range, to model the concept of doing something with every other, every third, etc., number in a range.
// do something with every integer i in [l,l+n,l+2*n,..u] for(int i = l; i<=u; i = i+n){ ... // do something with i }However, it is not suitable to use a
for-
statement to do
something with every floating-point number in [0.0, 0.1, 0.2, ..,
1.0] in the following way.
WARNING! Do not copy this bad example. // do something with every double d in [0.0, 0.1, 0.2,..,1.0] for(double d = 0.0; d<=1.0; d = d+0.1){ ... // do something with d }
This is because a floating-point number is just an approximation of a real number, and almost every time you make a floating-point arithmetic operation you loose a little more precision. In the example above we keep on making floating-point additions to d and for every operation d becomes more imprecise. However, integer operations in programming languages, if within the bounds of the used integer type, are always exact. Hence, if we rewrite the code above as follows even the last d that we do something with is only subject to one floating-point operation, instead of nine.
// do something with every double d in [0.0, 0.1, 0.2,..,1.0] for(int i=0; i<=10; i++){ double d = 0.1*i; ... // do something with d }
There are similar ways to construct most useful series of floating-point numbers.
try-catch
statement should have the following format:
try { statements; } catch (ExceptionClass e) { statements; }
A try-catch
statement may also be followed by finally
, which executes regardless of whether or not the try
block has completed successfully.
try { statements; } catch (ExceptionClass e) { statements; } finally { statements; }
if(a==B&&c==d||m==4) ...Always use spaces in assignements.
if(a==B && c==d || m==4) ...
if(a == B && c == d || m == 4) ...
moms = 25.0;
Variables should be named according to the following rules.
Identifier | To be written as |
---|---|
Class names | ClassNames |
Variable and method names | variableAndMethodNames |
Object names | objectNames |
Names of constants | NAMES_OF_CONSTANTS |
Use final variables instead:if (p.getX() < 300) // Don't
final double WINDOW_WIDTH = 300; . . . if (p.getX() < WINDOW_WIDTH) // OK
int level; // indentation level int size; // size of table
is preferred over
int level, size;
Do not put different types on the same line. Example:
int foo, fooarray[]; //WRONG!
Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.:
int level; // indentation level int size; // size of table Object currentEntry; // currently selected table entry
void myMethod() { int int1 = 0; // beginning of method block if (condition) { int int2 = 0; // beginning of "if" block ... } }
The one exception to the rule is indexes of for
loops, which in Java can be declared in the for
statement:
for (int i = 0; i < maxLoops; i++) { ... }
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:
int count; ... myMethod() { if (condition) { int count = 0; // AVOID! ... } ... }
When coding Java classes and interfaces, the following formatting rules should be followed:
class Sample extends Object { int ivar1; int ivar2; Sample(int i, int j) { ivar1 = i; ivar2 = j; } int emptyMethod() {} ... }
Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective. to be read by developers who might not necessarily have the source code at hand.
Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.
Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.
Note:The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.
Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.while (true) { ... }
.
should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands. Example:
a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } printSize("size is " + foo + "\n");
for
statement should be separated by blank spaces. Example:
for (expr1; expr2; expr3)
myMethod((byte) aNum, (int) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1);
Blank lines improve readability by setting off sections of code that are logically related.
One blank line should always be used in the following circumstances:
Table Of Content: JavaTM Code Conventions (Style guide)