You are on page 1of 17

JAVA Coding Practices Version 1 Dec -02-2011

General 1. Any of the following practices can be ignored for the following reasons: a. Your alternative is arguably an improvement in which case this document will be updated to reflect it. b. The code in question is a legacy piece of code that should be left as is per the grandfather clause. c. The code in question is a third party piece of code that is being reused or applied without modification. d. You have a valid reason for having an exception to the recommended practice.

General Naming Conventions 2. Names representing packages should be in all lower case: mypackage com.company.application.ui All packages should be named (by default): com.realdecoy.projectorclassname In some cases the company that owns the code will need their name to replace the realdecoy name. Names representing types, classes or interfaces should be nouns and written in mixed case starting with upper case Line AudioSystem Variable names must be in mixed case starting with lower case line audioSystem Names representing constants (final variables) must be all uppercase using underscore to separate words MAX_ITERATIONS COLOR_RED Names representing methods must be verbs and written in mixed case starting with lower case

3.

4.

5.

6.

7.

getName() computeTotalWidth() 8. Abbreviations and acronyms should not be uppercase when used as a name exportHtmlSource() openDvdPlayer() Private class variables should have underscore suffix class Person { private String name_; } Generic variables should have the same name as their type void setTopic(Topic topic) void connect(Database database) All names should be written in English. Variables with a large scope should have long descriptive names, variables with a small scope can have short names but not less than 3 characters. a. Possible exception being loop iterators, see below. The name of the object is implicit, and should be avoided in a method name. line.getLength(); // is specific enough line.getLineLength(); // redundant information

9.

10.

11. 12.

13.

Specific Naming Conventions 14. The terms get/set must be used where an attribute is accessed directly. employee.getName(); employee.setName(name); is prefix should be used for Boolean variables and methods. isSet isVisible Negated Boolean variable names must be avoided boolean isError // NOT: boolean isFound // NOT:

15.

16.

boolean isNoError boolean isNotFound

17.

The term compute can be used in methods where something is computed. valueSet.computeAverage matrix.computeInverse

18.

The term find can be used in methods where something is looked up. vertex.findNearestVertex(); matrix.findSmallestElement(); node.findShortestPath(Node destinationNode); The term initialize can be used where an object or a concept is established. printer.initializeFontSet(); JFC (Java Swing) variables should be suffixed by the element type. widthScale nameTextField leftScrollbar Plural form should be used on names representing a collection of objects. Collection<Point> points; int[] values; n prefix should be used for variables representing a number of objects, i.e. values that can be mathematically changed.. nPoints nLines No suffix should be used for variables representing an entity number, i.e. a value that represents an identifier like ID. tableNo employeeNo Iterator variables should be called I, j, k etc.. for (int i = 0; i < nTables; i++) { : } Complement names must be used for complement entities. a. get/set b. add/remove c. create/destroy d. start/stop e. insert/delete f. increment/decrement Abbreviations in names should be avoided. computeAverage(); // NOT:

19.

20.

21.

22.

23.

24.

25.

26.

compAvg()

ActionEvent event; command copy 27.

// NOT: // NOT: // NOT:

ActionEvent e cmd cp

Associated constants (final variables) should be prefixed by a common type name. final int COLOR_RED = 1; final int COLOR_GREEN = 2; final int COLOR_BLUE = 3; Exception classes must be suffixed with Exception Class AccessException extends Exception { : } Default interface implementations can be prefixed by Default. class DefaultTableCellRenderer implements TableCellRenderer { : } Singleton classes should return their sole instance through method getInstance. Class UnitManager { private final static UnitManager instance_ = new UnitManager(); private UnitManager() { } public static UnitManager getInstance() { // NOT: get() or instance() return instance_; } } Class that create instances on behalf of others (factories) can do so through method new[ClassName] class PointFactory { public Point newPoint() {

28.

29.

30.

31.

} } 32. The class name for a factory should be suffixed by the word Factory. class PointFactory { public Point newPoint() { } } Functions (methods returning an object) should be named after what they return and procedures (void methods) after what they do.

33.

Files 34. Java source files should have the extension .java. Point.java Java bytecode should have the extension .class. Point.class Classes should be declared in individual files with the file name matching the class name. Secondary private classes can be declared as inner classes and reside in the file of the class they belong to. File content must be kept within 80 columns. If you are exceeding that width consider if there are options to reduce the complexity of that section of code. Special characters (e.g. TAB and page break) must be avoided. Remove trailing whitespace from lines. The incompleteness of split lines must be made obvious. totalSum = a + b + c + d + e; method(param1, param2, param3);

35.

36.

37.

38. 39. 40.

Statements 41. Each line should contain at most one statement. argv++; // Correct argc--; // Correct

argv++; argc--; 42.

// AVOID!

The package statement must be the first statement of the file. All files should belong to a specific package. package java.awt; The import statements must follow the package statement. Import statements should be sorted with the most fundamental packages first and grouped with associated packages together and one blank line between groups. import java.io.IOException; import java.net.URL; import java.rmi.RmiServer; import java.rmi.server.Server; import javax.swing.JPanel; import javax.swing.event.ActionEvent;

43.

44.

Imported classes must always be listed explicitly. import java.util.List; // NOT: import java.util.*; import java.util.ArrayList; import java.util.HashSet; A return statement with a value should not use parantheses unless they make the return value more obvious in some way. return; return MyDisk.size(); return (size ? size : defaultSize);

45.

Classes and Interfaces 46. Classes and Interface declarations should be organized in the following manner: a. Class/Interface documentation. b. class or interface statement. c. Class (static) variables in the order public, protected, package (no access modifier), private. d. Instance variables in the order public, protected, package (no access modifier), private. e. Constructors f. Methods (alphabetical order).

Methods 47. Method modifiers should be given in the following order:

a. <access> static abstract synchronized <unusual> final native b. The <access> modifier (if present) must be the first modifier public static double square(double a); // NOT: static public double square(double a); Types 48. Type conversion must always be done explicitly. Never rely on implicit type conversion. floatValue = (float) intValue; // NOT: floatValue = intValue; Array specifiers must be attached to the type not the variable. int[] a = new int[20]; // NOT: int a[] = new int[20]

49.

Variables 50. Unless initialization causes ambiguity when analyzing results, variables should be initialized where they are declared and they should be declared in the smallest scope possible. This ensures that variables are valid at any time. Sometimes it is impossible
to initialize a variable to a valid value where it is declared. In these cases it should be left uninitialized rather than initialized to some phony value.

51.

Avoid assigning several variables to the same value in a single statement. Failing to do so leads to changes made on one variable affecting both. fooBar.fChar = barFoo.lchar = c; // AVOID! fooBar.fChar = c; // Correct barFoo.lChar = c; // Correct Variables should never have dual meaning. Dont reuse variables. Class variables should never be declared public. Variables should be kept alive for as short a time as possible.

52. 53. 54. Loops 55.

Only loop control statements must be included in the for() construction. sum = 0;// NOT: for (i = 0, sum = 0; i < 100; i++) for (int i = 0; i < 100; i++) { sum +- value[i]; sum += value[i]; } Loop variables should be initialized immediately before the loop. isDone = false; // NOT: bool isDone = false;

56.

while (!isDone) { : }

// // // //

: while (!isDone) : }

57. 58. 59.

The use of do-while loops should be avoided so the conditions are clearly at the start. The use of break and continue in loops should be avoided. Leverage for-each syntax when possible. Cars = parkingLot.getParkedCars(); for(Car car:cars) { car.doSomething(); } // NOT: Cars = parkingLot.getParkedCars(); int nCars = cars.size(); for(int i=0; i<nCars; i++) { Car car = cars[i]; car.doSomething(); }

Conditionals 60. Complex conditional expressions must be avoided. Introduce temporary Boolean variables instead. bool isFinished = (elementNo < 0 || elementNo > maxElement); bool isRepeatedEntry = (elementNo == lastElement); if (isFinished || isRepeatedEntry) { : } // NOT: if ((elementNo < 0 || (elementNo > maxElement) || elementNo == lastElement) { : } 61. The nominal case should be put in the if-part and the exception in the else-part of an if statement. boolean isOk = readFile(filename); if (isOk) { :

} else { : } 62. The conditional should be put on a separate line. if (isDone) { // NOT: if (isDone) doCleanup(); doCleanup(); } Executable statements in conditionals must be avoided. InputStream stream = File.open(filename, w); if (stream != null) { : } // NOT: if (File.open(filename, w) != null)) { : } Miscellaneous 64. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1 can be considered declared as named constants instead. Private static final int TEAM_SIZE = 11; : Player[] players = new Player[TEAM_SIZE]; // NOT: Player[] players = new Player[11]; Floating point constants should always be written with decimal point and at least one decimal. double total = 0.0; // NOT: double total = 0; double speed = 3.0e8; // NOT: double speed = 3e8; double sum; : Sum = (a + b) * 10.0; Floating point constants should always be written with a digit before the decimal point. double total = 0.5; // NOT: double total = .5; Static variables or methods must always be referred to through the class name and never through an instance variable. Thread.sleep(1000); // NOT: thread.sleep(1000);

63.

65.

66.

67.

68.

Text encoding should be UTF-8

Layout 69. Basic indentation should be 2 spaces (no tabs) for (i = 0; i < nElements; i++) { a[1] = 0; } Block layout should be as illustrated in example 1 below (recommended) or example 2, and must not be as shown in example 3. Class, Interface and method blocks should use the block layout of example 2. while (!isDone) { doSomething(); done = moreToDo(); } // NOT: while (!isDone) { doSomething(); done = moreToDo(); } // OR while (!isDone) { doSomething(); done = moreToDo(); }

70.

71.

The class and interface declarations should have the following form: class Rectangle extends Shape implements Cloneable, Serializable { } Method definitions should have the following form: public void someMethod() throws SomeException {

72.

} 73. The if-else class of statements should have the following form: if (condition) { statements; } if (condition) { statements; } else { statements; } 74. The for statement should have the following form: for (initialization; condition; update) { statements; } The while statement should have the following form: while (condition) { statements; } The do-while (if used, noting above recommendation to avoid their use) should have the following form: do { statements; } while (condition); The switch statement should have the following form: switch (condition) { case ABC : statements; // Fallthrough case DEF : statements; break; case UVW : case XYZ : statements; break;

75.

76.

77.

default : statements; break; } 78. A try-catch statement should have the following form: try { statements; } catch (Exception exception) { statements; } finally { statements; } Single statement if-else, for or while statements cannot be written without brackets. if (condition) { statement; } while (condition) { statement; } for (initialization; condition; update) { statement; } White Space 80. General spacing: a. Binary operators should be surrounded by a space character. b. Java reserved words should be followed by a white space. c. Commas should be followed by a white space. d. Colons should be surrounded by white space. e. Semicolons in for statements should be followed by a space character. a = (b + c) * d; // NOT: a=(b+c)*d; while (true) { // NOT: while(true){ doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d); case 100 : // NOT: case 100: for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){ Method names can be followed by a white space when it is followed by another name. doSomething (currentFile);

79.

81.

82.

Logical units with a block should be separated by one blank line. // Create a new identity matrix Matrix4x4 matrix = new Matrix4x4(); // Precompute angles for efficiency double cosAngle = Math.cos(angle); double sinAngle = Math.sin(angle); // Specify matrix as matrix.setElement(1, matrix.setElement(1, matrix.setElement(2, matrix.setElement(2, a rotation transformation 1, cosAngle); 2, sinAngle); 1, -sinAngle); 2, cosAngle);

// Apply rotation transformation.multiple(matrix); 83. 84. Methods should be separated by three blank lines. Variables in declarations can be left aligned TextFile file; int nPoints; double x; Statements should be aligned where this enhances readability. These are on occasion exceptions to regular spacing rules. if (a == lowValue) compueSomething(); else if (a == mediumValue) computeSomethingElse(); else if (a == highValue) computeSomethingElseYet(); value = (potential * oilDensity) / constant1 + (depth * waterDensity) / constant2 + (zCoordinateValue * gasDensity) / constant3; minPosition = computeDistance(min, x, y, z); averagePosition = computeDistance(average, x, y, z); switch case case case } Comments (phase) { PHASE_OIL : text = "Oil"; break; PHASE_WATER : text = "Water"; break; PHASE_GAS : text = "Gas"; break;

85.

86.

All classes and constructors should have Javadoc-style comments that describe their purpose. /** * [Class Description] * */ Tricky code should not be commented but rewritten. All comments and code should be written in English, with proper grammar and correct spelling. Javadoc comments should have the following form: /** * Return lateral location of the specified position. * If the position is unset, NaN is returned. * * @param x X coordinate of position. * @param y Y coordinate of position. * @param zone Zone of position. * @return Lateral location. * @throws IllegalArgumentException If zone is <= 0. */ public double computeLocation(double x, double y, int zone) throws IllegalArgumentException { ... } // OR /** Number of connections to this database **/ private int nConnections_; There should be a space after the comment identifier // This is a comment // NOT: //This is a comment /** * This is a javadoc * comment */ NOT: /** *This is a javadoc *comment */

87. 88.

89.

90.

91.

Use // for all non-JavaDoc comments, including multi-line comments. // Comment spanning // more than one line.

92.

Comments should be indented relative to their position in the code. while (true) { // do something Something(); } // NOT while (true) { // do something Something(); }

93.

The declaration of anonymous collection variables should be followed by a comment stating the common type of the elements of the collection. private Vector points_; // of Point private Set shapes_; // of Shape All public classes and public and protection functions within public classes should be documented using the Java documentation (javadoc) conventions.

94.

Error Handling 95. A failure should never leave a class in an undefined state. An error should be detected and handled if it affects the execution of the rest of a routine. a. For example, if you try to allocate a resource and it fails, this affects the rest of the routine if it uses that resource. Dont design a routine where error conditions are identified as a special case of an out parameter. Instead, use a specific error condition parameter. a. For example, try and avoid methods that return null to identify a specific error case When possible, use exceptions to handle errors and unexpected results instead of returning a special value to denote what happened. The case where you would not do this is for a black box API. Public String getResult() throws CustomException { if (success) { return success message; } else { throw new CustomException (error message); } }

96.

97.

// instead of Public Result getResult() { if (success) { Result result = new Result (success message, 0); return result; } else { Result result = new Result (error message, 1); return result; } } 98. All public methods should validate their arguments and throw an exception. if (id < 1) { throw IllegalArgumentException (ID less than one.); } if (title == null || title.isEmpty()) { throw IllegalArgumentException (Title null or empty); } Dont return inside blocks, it makes it difficult to find. For example the flow of execution in a try/catch block may not be obvious because the finally clause always executes. Foo bar = null; try { bar = this.thingy.getFoo(); } catch (FooException e) { log.error (Thingy broke., e); throw e; } finally { this.thingy.close(); } return bar; // NOT try { return this.thingy.getFoo(); } catch (FooException e) { log.error (Thingy broke., e); throw e; } finally { this.thingy.close(); }

99.

Sources 1. 2. 3. 4. The staff of Real Decoy http://geosoft.no/development/javastyle.html http://www.asjava.com/core-java/java-coding-standards-and-best-practices-2/ http://www.macadamian.com/insight/best_practices_detail/coding_conventions_for_c_and_ja va 5. http://www.javapractices.com/home/HomeAction.do 6. http://www.oracle.com/technetwork/java/codeconvtoc-136057.html

You might also like