Styling conventions

For Java

1.     Definitions

1.1.    A line is a single line in the code, containing zero or more characters, comments or statements.

1.2.    Indentation is 4 spaces or a single tab. A level of indentation reflects the number of indentations: one level deeper means one more indentation means 4 more spaces (or one more tab).

1.3.    A code block is code which is surrounded by curly braces { and }.

1.4.    A block statement is a statement that includes a code block.

1.5.    Naming subjects are parts of the code which we can choose their names: types, variables, parameters, methods, etc.

1.6.    Casing:

1.6.1. camelCasing: capitalize only the first letter of each word, except the first one.

1.6.2. PascalCasing: capitalize only the first letter of each word.

1.6.3. ALL_CAPITALS: all the letters are capital.

1.6.4. no_capitals: no letter is capitalized.


 

2.     General indentation & appearance rules

2.1.    Every line should be indented the same as the line above it, except the cases below.

Good

Bad

    System.out.println(“Line 1”);

    System.out.println(“Line 2”);

    System.out.println(“Line 1”);

        System.out.println(“Line 2”);

 

2.2.    The following statements should not be indented at all when they are the highest level statement in a file:

2.2.1. ‘package’ and ‘import’

2.2.2. Types, such as ‘class’, ‘interface’ and ‘enum’

2.2.3. Type documentation

Good

Bad

package il.ac.idc.turtle;

import java.util.Scanner;

 

/**

 * This class draws a Turtle…

 */

public class Turtle {

package il.ac.idc.turtle;

       import java.util.Scanner;

 

/**

 * This class draws a Turtle..

 */

       public class Turtle {

 

2.3.    Block statements:

2.3.1. The opening brace comes at the end of the same line of the block statement (separated with a single space).

2.3.2. Indent the entire code block one level deeper than the statement line.

2.3.3. The closing brace should be on a separate line right after the last non-blank line of the code block, indented the same as the statement line.

Good

Bad

public int foo(int i) {

       System.out.println(“bar”);

       while (i > 0) {

              System.out.print(“and again”);

       }

}

public int foo(int i)

{

              System.out.println(“bar”);

       while (i > 0) {

              System.out.print(“and again”);}

   }

 

2.4.    Do not write multiple statements in the same line. Concatenating statements is allowed.

Good

String u = (new Scanner(System.in)).nextLine().trim();

System.out.print(“Upper version: “);

System.out.println(u);

Bad

String u = (new Scanner(System.in)).nextLine().trim();

System.out.print(“Upper version: “); System.out.println(u);

 

2.5.    Line wrapping:

2.5.1. Keep lines no longer than 80 characters (assuming a tab of 4 spaces long).

2.5.2. If a statement is longer than 80 characters, break it according to these rules:

2.5.2.1.              Prefer breaking a higher level statement than a lower level.

2.5.2.2.              Before an operator.

2.5.2.3.              After a comma.

2.5.2.4.              After an opening parenthesis.

2.5.2.5.              Within a long String and concatenate.

2.5.2.6.              Preserve logics; if several breaks needed for a single statement, prefer keeping logical groups in each line.

2.5.3. After a line break, indent the second line one level deeper than the statement (not the line) that was broken. If the second line requires more breaking, indent the next lines at the same level as the second line.

Good

Bad

float x = 3f;

float y = 10f;

float z = Math.sqrt(Math.pow(x, 2))

              * ((x + y) / 2)

              / Math.abs(x – y);

float x = 3f;

float y = 10f;

float z = Math.sqrt(Math.pow(x, 2)) * ((x + y)

       / 2)

              / Math.abs(x – y);

 

2.6.    End a file with a closing brace and (optionally) followed by a single blank line.


 

3.     Documentation

3.1.    Assume these documentation comments:

3.1.1. BC: Block comment (conforming to the Javadoc standard)

BC

/**

 * First line of comment.

 * Second line of comment.

 * Last line of comment

 *

 * @author Boaz Kantor

 */

Commented subject

 

3.1.2. SLBC: A single line block comment

SLBC

/** One line of comment */

Commented subject

 

3.1.3. IC: An internal comment above code

IC

// one line of comment

Commented subject

 

3.1.4. EC: An ending comment

SLBC

Commented subject // short comment

 

3.2.    BC and SLBC should describe the role of the commented subject, ignoring the implementation. IC and EC should describe the implementation of the commented subject.

3.3.    Each method or type (class, enum, interface, etc) is preceded by a BC.

Good

Bad

/**

 * Represents a clock, which supports hours,

 * minutes and seconds.

 */

public class Clock {

/**

 * Represents a clock, which supports hours,

 * minutes and seconds, implemented as a long

 * variable which represents the seconds passed

 * since midnight, 1/1/1970.

 */

public class Clock {

 

3.4.    Each constant is preceded by a SLBC.

Good

Bad

/** Denotes the last hour in a day */

private static final int MAX_HOURS = 23;

// Denotes the last hour in a day

private static final int MAX_HOURS = 23;

 

3.5.    Precede each logical piece of code with an IC.  Logical pieces of code are:

3.5.1. Sections within a method (local variables, parameter validation and algorithm)

3.5.2. A logical short section. Usually 2-5 lines of code, rarely a single line.

3.5.3. Control structure statements.

Good

Bad

public void foo(int bar) {

 

       // validate parameters

       Validation code

 

       // handle input values

       switch (bar) {

 

public void foo(int bar) {

       validation code

 

       // increase bar once

       bar++;

 

       switch (bar) {

 

3.6.    Some statements may require an EC. This may occur with variable declarations, case statements, else statements and others.

Good, example

       switch (bar) {

              case 0:       // handle this

                     break;

              case 1:       // handle that

                     break;

              default:      // internal bug

                     break;

       }

 

 

3.7.    If several consecutive lines require an EC, prefer indenting the EC’s the same. Otherwise separate the EC from the statement with a single space or tab.

Good

Bad

public void foo(int bar) {

 

       int var1;     // temporary variable

       float var2;   // algorithm result

       String c;     // error message

 

public void foo(int bar) {

      

       int var1;// temporary variable

       float var2;   // algorithm result

       String c; // error message

 

 

3.8.    Separation from the rest of the code:

3.8.1. Attach a comment line to the first line of the commented section.

3.8.2. Separate comment line from the code above with a single blank line.

3.8.3. Separate commented section from the code below with a single blank line.

3.8.4. Indent comments the same as the commented code.

Good

Bad

public void foo(int bar) {

 

       // validate parameters

       Validation code

 

       // handle input values

       switch (bar) {

 

public void foo(int bar) {

 

 

       // validate parameters

       Validation code

              // handle input values

       switch (bar) {

 

 


 

4.     Naming

4.1.    Choose a name that describes the role of the subject, and not the value it holds.

Good

Bad

public float average(int[] grades) {

       int currentSum = grades[0];

       float average = 0;

 

       for (int currGrade : grades) {

public float floatAverage(int[] nums) {

       int first = grades[0];

       float zero = 0;

 

       for (int i : grades) {

static final int DEFAULT_SELECTION = 0;

static final int ZERO = 0;

 

4.2.    Avoid single-letter names.

Good

for (int currLine = 0; currLine < vec.length; ++currLine) {

       for (int currElement = 0; currElement < vec.length; currElement++) {

Bad

for (int i = 0; i < vec.length; ++i) {

       for (int j = 0; j < vec.length; j++) {

 

4.3.    Names should not be too short and not too long.

Good

Bad

int currSum;

int x;

float result;

float resultToBeReturnedAtTheEnd;

String errorMessage;

String msg;

Scanner inputLineFormatter;

Scanner sc;

 

4.4.    Avoid using special characters (like underscore) in names. Keep names as characters and numbers only, with the exception of ‘all-capitals’ and ‘no-capitals’ names (see capitalization below).

Good

Bad

private static final int FINAL_NAME = 10;

private static final int _FINALNAME_ = 10;

public class ClassName {

       public void methodName(int paramName) {

public class Class_Name {

       public void _methodName(int ParamName) {

package il.ac.idc.turtle;

package il.ac.idc.Turtle_;

int localVarName;

int Local_varname;

enum TypeName {

       ENUM_VALUE,

enum type_name {

       enumValue,

 

4.5.    Avoid abbreviations.

Good

Bad

int numberOfStudents

int nStdnts;

 

4.6.    Prefer initials.

Good

Bad

String pageUrl;

String pageUniformResourceLocator;

 

4.7.    Capitalization rules:

4.7.1. Initials are capitalized as a single word.

4.7.2. Constant variables, enum values: ALL_CAPITALS, separate words with underscores.

4.7.3. Local variables, instance variables, parameters, methods: camelCasing.

4.7.4. Classes, files, enums, interfaces: PascalCasing.

4.7.5. Packages: no_capitals, separate words with underscores.

Good

Bad

int pageUrl;

int pageURL;

final int FINAL_OR_ENUM_VALUE

final int FinalOr__ENUM__VALUE_;

void methodName(int fooBar) {

void MethodName(int _foo_BAR) {

enum TypeNameCasing {

enum typeNameCASING {

package il.ac.idc.gremlins_grafx;

package il.ac.IDC.GremlinsGrafx;

 

5.     Expressions

5.1.    Separate binary and ternary operators from operands with a single space on both sides.

Good

Bad

x + y / z > 0 ? true : false;

x+y/z>0?true:false;

 

5.2.    Parentheses:

5.2.1. Separate parentheses from the outside with a single space.

5.2.2. Do not separate parentheses from the inside.

5.2.3. If a parenthesized expression begins or ends with another parenthesis, attach them (no space).

Good

Bad

((x + y) / z) > 0 ? true : false;

( ( x + y ) / z ) > 0 ? true : false;

 

5.3.    Use parentheses only if it’s required by a statement or if it makes the code clearer.

Good

Bad

x = x * y / 2;

x = ((x * y) / 2);

if ((x + 3 > 0) || (y < (x – 4) / 2) && !foo()) {

if ((x + 3) > 0 || y < x – 4 / 2 && (!foo()) {

 

5.4.    Avoid using == true and == false in boolean expressions.

Good

Bad

if (x > 0) {

if (x > 0 == true) {

if (!obj.isUp()) {

if (obj.isUp() == false) {

 


 

6.     Statements

6.1.    Variable declaration:

6.1.1. Each variable should be declared in a separate line.

6.1.2. Array brackets should be attached to the right of the array type.

Good

Bad

int x;

int y;

float[] z;

int x, y;

float z [];

 

6.2.    Assignment statements:  separate the equal operator with a single space in both sides.

Good

Bad

someVar = foo();

someVar=foo();

 

6.3.    Casting:

6.3.1. Attach the cast parentheses both to the cast type and the casted subject.

6.3.2. Avoid surrounding the casted subject with parentheses, unless required by the code.

Good

Bad

(int)floatVar;

(int) (floatVar);

(int)(obj.getAverage());

((int)(obj.getAverage));

 

6.4.    Method calls:

6.4.1. Attach the opening parenthesis to the method name (no space).

6.4.2. Do not separate parentheses from parameters.

6.4.3. If several parameters are written, attach the comma to the previous parameter and separate it from the next parameter by a single space.

6.4.4. Attach the dot on either side (no spaces).

Good

Bad

foo.bar(param1, param2, param3);

foo .bar( param1,param2 , param3);

 

6.5.    Return statement: avoid surrounding the returned value with parentheses, unless it makes the code much more clear.

Good

Bad

return (x > y ? x : y);

return x > y ? x : y;

return myDisk.size();

return (myDisk.size());

 


 

7.     Flow control statements

7.1.    ‘if’ statement:

General form

if (boolean condition) {

       // code block

}

if (boolean condition) {

       // code block

} else {

       // code block

}

if (boolean condition) {

       // code block

} else if (boolean condition) {

       // code block

} else if (boolean condition) {

       // code block

}

 

7.1.1. Always surround the ‘if’ and ‘else’ blocks with braces, even if it’s only one line.

Good

Bad

if (boolean condition) {

       x = 3;

} else {

       x = 0;

}

if (boolean condition)

       x = 3;

else x = 0;

 

7.2.    ‘for’ statement:

General form

for (init1, init2; condition; step1, step2) {

       // iteration code

}

for (Type name : collection) {

       // iteration code

}

for (init1, init2; condition; step1, step2);

 

7.3.    ‘while’ statement:

General form

while (boolean condition) {

       // iteration code

}

do {

       // iteration code

} while (boolean condition);

while (boolean condition);

 

7.4.     ‘switch’ statement:

General form

switch (value) {

       case v1:

              // case code

              break;

       case v2:

              // case code

              break;

       default:

              // case code

              break;

}

 

7.4.1. Cases that don’t end with a break statement (fallthrough) should have an IC comment “fallthrough” where the break statement would normally be.

Good

Bad

switch (var1) {

       case 0:

              System.out.println(var1);

              // fallthrough

       case 1:

              // fallthrough;

       case 2:

              var1++;

              break;

       default:

              break;

}

switch (var1) {

       case 0:

              System.out.println(var1);

       case 1:

       case 2:

              var1++;

              break;

       default:

              break;

}

 


 

8.     Order of statements

8.1.    If a class is part of a package, the ‘package’ statement is the first line of the file.

8.2.    Import:

8.2.1. Import statements come first in a file, unless there is a package statement.

8.2.2. Import Java libraries first. Sort alphabetically.

8.2.3. Import project own packages second. Sort alphabetically. Separate from Java libraries with a single blank line.

8.3.    Class:

8.3.1. Class comment.

8.3.2. Class declaration (attached to the class comment).

8.3.3. Class Enums.

8.3.4. Static variables (and constants):  public, then protected then private.

8.3.5. Instance variables.

8.3.6. Empty constructor.

8.3.7. Other constructors.

8.3.8. Public methods:

8.3.8.1.              Getters and setters (each getter right after a corresponding setter).

8.3.8.2.              Other public methods.

8.3.9. Private methods.

8.3.10.    Closing brace.

8.3.11.    A single empty line.

8.4.    Enums:

8.4.1. Enum comment.

8.4.2. Enum declaration line, attached to the comment, followed by an opening brace, separated from the declaration line with a single space.

8.4.3. Each value is in its own line. Attach the comma to the end of a value.

8.5.    Methods:

8.5.1. Methods are separated from the rest of the code with a single blank line.

8.5.2. Method comment.

8.5.3. Declaration line, followed by an opening brace.

8.5.4. Parameter validation.

8.5.5. Local variables (when possible).

8.5.6. Algorithm.

8.5.7. Return statements can be multiple and anywhere in the algorithm.

8.5.8. Closing brace.

Order of statements, example (excluding comments)

package pack1;

 

import java.sql;

import java.util.logging;

import java.util.Scanner;

 

import pack2;

import pack3;

 

public class MyClass {

 

       public enum Actions {

              TALK,

              SHOUT,

              WHISTLE,

              SHUDDUP

       }

 

       public static final Actions DEFAULT_ACTION = Actions.TALK;

       public static final int MAX_ACTIONS = 10;

       private static final int FIRST_ACTION = Actions.SHUDDUP;

 

       private Actions currentAction;

       private ArrayList<Actions> allActions = new ArrayList<Actions>();

 

       public MyClass() {

              // default constructor implementation

       }

 

       public MyClass(Actions action) {

              // another constructor implementation

       }

 

       public void setCurrentAction(Actions action) {

              // setter

       }

 

       public Actions getCurrentAction() {

              // getter

       }

 

       public boolean shout(String message) {

              if (message == null) {

                     foo();

                     return false;

              }

 

              boolean result = false;

              String someInterimString = “”;

 

              // algorithm comes here

 

              return result;            

       }

 

       public String toString() {

              String result = “”;

              // build the result;

              return result;

       }

 

       private void foo() {

              bar();

       }

 

       private int bar() {

              // implementation

       }

}

 

 

 

© 2010, written by Boaz Kantor for IDC Herzliya.