Java Coding Guidelines - Part B PDF Print E-mail


3         Naming Conventions


3.1      General


Choosing good names to designate code entities (packages, classes, variables, annotations, enumerations, etc) is one of the most delicate issues to address in all software applications. In medium-to-large applications, another problem arises: conflicts in names, or rather the difficulty in finding enough synonyms to designate distinct but similar notions about the same real-world concept.


Choose clear, legible, meaningful names.


Unlike many other programming languages, Java does not limit the length of identifiers. Speed of typing is not an acceptable justification for short names. Generally, use full names rather than abbreviations.


Abbreviations or short names are tolerated less for artefacts with larger scopes. There might be a few exceptions, such as using E for the base of the natural logarithms, Pi, or a handful of other well-recognized cases. Using i and j in simple integer based iterations is also generally well accepted and does not contravene these guidelines due to their small scope. Using e for exception objects is also a well accepted practice.


Express names so that they read well from the usage point of view. An entity is declared once and used many times. This is especially true for attributes, method names and their parameters.

3.2      Packages


Package names should be in lower case and prefixed by organization identification.

package com.mycompany.infrastructure.util


3.3      Types


Names representing types must be nouns and written in mixed case starting with upper case.


When a class specifies an interface or some grouping of functionality, and does not relate to an object, express this in the name:

class CustomerManagerInterface …

class MathDefinitions …

class CoordinateOperations …


3.4      Methods


Method names must be in mixed case starting with lower case.


Use verbs for methods that change the state of the class.


Use method names setXxxx and getXxxx when there is little processing involved. If the method simply involves setting or returning an attribute, then Xxxx should be identical to the attribute and parameter or return name. If processing is significant, use a name to imply the non trivial nature of the operation such as findXxxx or computeAverage().


void setName(final String name) { = name;


String getName() {

   Return name;


Coordinate computeAverage() {



List<Node> findShortestPath(final Node fromNode, final Node toNode) {





Use positive names for predicate methods and boolean parameters. Using negative names can create double negations (e.g., not isNotFound), and can make the code more difficult to read.


boolean hasFirstName()

boolean isAdministrator()

boolean isFirst()

boolean hasLicense()

boolean canExecute()

boolean shouldTerminate()

String firstNameOf()

Date creationDateOf()


Complementary names should be used for complementary operations such as get/set, first/last, min/max, next/previous, old/new, begin/end, increment/decrement, add/remove, etc.


Use the same word when the same general meaning is implied, rather than trying to find synonyms or variations. Overloading therefore is encouraged to enhance uniformity, in keeping with the principle of minimal surprise.


Since Java does not support named parameter association, do not pass in unnamed values to methods. Instead, name the parameters using local variables as in the following example:


void createAdministrator() {

   String name = “fred”;

   String password = “wilma”;

   boolean dministrator = true;

   createUser(name, password, administrator)



3.5      Objects


Exported constants should be in upper case separated by underscores.


The names of variables and constants with limited visibility must be in mixed case starting with lower case.


public static final String MINUTES_PER_HOUR = 60;

private static final Logger logger = Logger.getLogger(CoordinateOperations.class);

private final SessionHandle sessionHandle;

private Connection connection = null;


For boolean objects, use a predicate clause, with the positive form:


Boolean foundIt;

Boolean isAvailable;



For thread objects, use a noun or noun phrase that implies an active entity:


Thread listener;

Thread resourceManager;


Generic variables should have the same name as their type. For example, replace:


void connect(Database db) {




void connect(Database database) {


Non-generic variables have a role. These variables can often be named by combining role and type:


Coordinate centreCoordinate;

Layer topLayer;



3.6      Exceptions


Exception names should end in either “Exception” or “Error” depending on whether they subclass “java.lang.Exception” or “java.lang.Error” respectively.


4         Declarations


Generally, reduce the scope of objects as much as possible.


Class attributes should always be private. One exception to this rule is where the class is essentially a simple data structure (like a C++ struct) such as class Point with public int attributes x and y.


Initialize local variables where they are declared.


Java's strong typing facility is used to prevent mixing of different types.


Declare objects in the most abstract form appropriate. For example, instead of declaring an object of type HashSet, declare it of type Set.


Minimize using null as a valid state of a class. Instead, define a “nil” instance of the class. Using null is acceptable where no “nil” version is appropriate or initialisation of a nil instance will result in performance problems.


Specify initial values in object declarations (locals or attributes) wherever possible.


Declare objects as final wherever appropriate to avoid accidental assignment or no initialisation.


Avoid the use of literal values in the code. Define related constants with universal, static expressions:


public static final PI = 3.1415926535897;

private static final int bytesPerPage = 512;

private static final int pagesPerBuffer = 10;

private static final int bufferSize = bytesPerPage * pagesPerBuffer;


Declare maps with names such that the key and value types are evident. For example:


private final Map<String, Street> streetsByName = HashMap<String, Street>();


5         Structure and Organisation


The structure and organisation of code should be specified during the design phase.

5.1      Classes


Each Java source file should contain only one outer class.


Limit the number of operations provided by a class.


Limit the size of classes as large classes are cumbersome and require more merging in a team environment.


Limit the number of interfaces a single class implements. For example, use private nested classes to implement “listener” type interfaces.


5.2      Methods


Methods should not be more than about 30 lines long.


6         Expressions and Statements


6.1      Logic Statements


Use redundant parentheses when needed to make compound expressions clearer.


Use case statements when the expression evaluates to non Boolean discrete types.


Include default statements within case statements to handle unexpected case conditions.


Use simple boolean expressions in place of "if else" statements for simple predicates. For example, replace:


if (theValue > 0 && theValue < maxValue) {

   validInput = true;

} else {

   validInput = false;





validInput = theValue > 0 && theValue < maxValue;


Complex expressions containing two or more if statements should not be changed in this manner if it affects readability.


Where applicable, provide else statements to show the alternate condition has been thought of. For example:


if (roadFound) {


} else {

   // ignore roads that don’t exists



Do not have empty else statements where it is obvious the alternate condition requires no processing. For example:


if (logger.isDebugEnabled()) {






<< Back    Continued >>

< Prev   Next >