Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Recommenders/CodingConventions

Contents

Introduction

This document lists Java coding recommendations common in the Java development community. This text is a copy of http://geosoft.no/development/javastyle.html and slightly adopted for the code recommenders project. The recommendations described here are based on established standards collected from a number of sources, individual experience, local requirements/needs, as well as suggestions given in.

Layout of the Recommendation.

The recommendations are grouped by topic and each recommendation is numbered to make it easier to refer to during reviews.

Layout for the recommendations is as follows:

  1. n. Guideline short description
  2. Example if applicable
  3. Motivation, background and additional information.

The motivation section is important. Coding standards and guidelines tend to start "religious wars", and it is important to state the background for the recommendation.

Recommendation Importance

In the guideline sections the terms must, should and can have special meaning. A must requirement must be followed, a should is a strong recommendation, and a can is a general guideline.

Automatic Style Checking

Many tools provide automatic code style checking and automated code formatting. Checkstyle by Oliver Burn is probably one of the most popular of such tools. An Eclipse integration for Checkstyle can be found here http://eclipse-cs.sourceforge.net.

To use Checkstyle with Code Recommenders guidelines please use this xml configuration file: <TODO> 

General Recommendation

Any violation to the guide is allowed if it enhances readability.

The main goal of the recommendation is to improve readability and thereby the understanding and the maintainability and general quality of the code. It is impossible to cover all the specific cases in a general guide and the programmer should be flexible.

No code without license header!

At Eclipse every java source code file (at least) needs an EPL license header BEFORE it is checked in. The typical license header looks like this:

/**
 * Copyright (c) 2010 Darmstadt University of Technology.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Marcel Bruch - initial API and implementation.
 */
package org.eclipse.recommenders.internal.rcp.codecompletion;

import ...
public class CompilerAstCompletionNodeFinder extends ASTVisitor {
  ...
}

Adopt the copyright header and Contributors section according to your affiliation and name. Inform your build master if you are using a new license. Otherwise it may break the build.

No check-in without running mvn clean install locally.

$ pwd
/Users/Marcel/Workspaces/code-recommenders/public/org.eclipse.recommenders.parent
$ mvn clean install
... wait a few minutes and check the build results

The one who breaks the build... you already know what happens, right?

Naming Conventions

General Naming Conventions

Names representing packages should be in all lower case.

 mypackage, com.company.application.ui 

Package naming convention used by Sun for the Java core packages. The initial package name representing the domain name must be in lower case.


Eclipse Package Naming Conventions

At Eclipse there are a set of naming conventions described in great detail here:

A bief summary of this discussion for code recommenders is:

All packages start with:

org.eclipse.recommenders.*

Internal packages always start with

org.eclipse.recommenders.internal.* // NOT org.eclipse.recommenders.other.package.internal;
  // NOT org.eclipse.recommenders.other.internal.package;

Test packages start with

org.eclipse.recommenders.tests.* // NOT org.eclipse.recommenders.other.package.tests;
  // NOT org.eclipse.recommenders.other.tests.package;


Example packages start with

org.eclipse.recommenders.examples.* // NOT org.eclipse.recommenders.other.package.examples;
  // NOT org.eclipse.recommenders.other.examples.package;

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

Line, AudioSystem

Common practice in the Java development community and also the type naming convention used by Sun for the Java core packages.

Interfaces follow the Eclipse Style I[TypeName] convention

public interface IVariableUsageResolver // NOT just VariableUsageResolver
{
 ...
}

The I[TypeName] convention allows developers to quickly assess the relevant interfaces in a package. Like it or not - this is an Eclipse convention we have to obey.

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

line, audioSystem

Common practice in the Java development community and also the naming convention for variables used by Sun for the Java core packages. Makes variables easy to distinguish from types, and effectively resolves potential naming collision as in the declaration Line line;

Names representing constants (final variables) must be all uppercase using underscore to separate words.

MAX_ITERATIONS, COLOR_RED

Common practice in the Java development community and also the naming convention used by Sun for the Java core packages.

TODO :Add section about enums

Names representing methods must be verbs and written in mixed case starting with lower case.

getName(), computeTotalWidth()

Common practice in the Java development community and also the naming convention used by Sun for the Java core packages. This is identical to variable names, but methods in Java are already distinguishable from variables by their specific form.

Abbreviations and acronyms should not be uppercase when used as name.

exportHtmlSource(); // NOT: exportHTMLSource();
openDvdPlayer(); // NOT: openDVDPlayer();

Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type whould have to be named dVD, hTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readability is seriously reduced; The word following the acronym does not stand out as it should.

TODO

liste der Standard abkürzungen:

ast -> jdt.deom rec -> recommenders jdt -> IJavaElement compiler -> compiler internal

cu -> compilationUnit -> preferred compilationUnit (no abbrev)

Private class variables must not have any field prefix or suffix.

class Person
{
  private String name; // NOT private String _name;
  // NOT private String fName;
// NOT private String name_;
  ...
}


void setName(String name)
{
  this.name = name; // NOT name_= name;
}

To eliminate misinterpretations qualify field puts with this. and use the same names. Use IDE highlighting settings to make more visible on which kind of variable you are working.

TODO

Generic variables should have the same name as their type.

void setTopic(Topic topic) // NOT: void setTopic(Topic value)
  // NOT: void setTopic(Topic aTopic)
  // NOT: void setTopic(Topic t) 

void connect(Database database) // NOT: void connect(Database db)
  // NOT: void connect(Database oracleDB)

Reduce complexity by reducing the number of terms and names used. Also makes it easy to deduce the type given a variable name only. If for some reason this convention doesn't seem to fit it is a strong indication that the type name is badly chosen.

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

Point startingPoint, centerPoint;
Name loginName;

All names should be written in English.

English is the preferred language for international development.

Variables with a large scope should have long names, variables with a small scope can have short names

Scratch variables used for temporary storage or indices are best kept short. A programmer reading such variables should be able to assume that its value is not used outside a few lines of code. Common scratch variables for integers are i, j, k, m, n and for characters c and d.

The name of the object is implicit, and should be avoided in a method name.

line.getLength(); // NOT: line.getLineLength();

The latter might seem natural in the class declaration, but proves superfluous in use, as shown in the example.

Specific Naming Conventions

The terms get/set must be used where an attribute is accessed directly.

employee.getName();
employee.setName(name);

matrix.getElement(2, 4);
matrix.setElement(2, 4, value);

Common practice in the Java community and the convention used by Sun for the Java core packages. Getters should not change the internal state of the object. Exceptions may be lazy initializers. Getter should actually return something :-)

NOTE: this is a pure GET. No real computation effort needed.

is prefix should be used for boolean variables and methods.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Sun for the Java core packages. Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.

Setter methods for boolean variables must have set prefix as in:

void setFound(boolean isFound);

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

The term compute can be used in methods where something is computed.

valueSet.computeAverage();
matrix.computeInverse()

Give the reader the immediate clue that this is a potential time consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.

The term find can be used in methods where something is looked up.

vertex.findNearestVertex();
matrix.findSmallestElement();
node.findShortestPath(Node destinationNode);

Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability.

The term initialize can be used where an object or a concept is established.

printer.initializeFontSet();

The American initialize should be preferred over the English initialise. Abbreviation init should be avoided.


The use of initializeXYZ() in constructors to initialize complex fields is preferred over direct field initalizations.


Set<Statements> supportedCompletionRequests;
  // NOT Set<Statements> supportedCompletionNodes = createSupportedCompletionRequest()

public CallsCompletionEngine(..) {
  ...
  initializeSuportedCompletionRequests();
}

private void initializeSuportedCompletionRequests() 
{
  supportedCompletionRequests = Sets.newHashSet();
  supportedCompletionRequests.add(CompletionOnMemberAccess.class);
  supportedCompletionRequests.add(CompletionOnMessageSend.class);
  supportedCompletionRequests.add(CompletionOnQualifiedNameReference.class);
  supportedCompletionRequests.add(CompletionOnSingleNameReference.class);
}

JFC (Java Swing) and SWT variables should be suffixed by the element type.

widthScale, nameTextField, leftScrollbar, mainPanel, fileToggle, minLabel, printerDialog

Enhances readability since the name gives the user an immediate clue of the type of the variable and thereby the available resources of the object.

Plural form should be used on names representing a collection of objects.

Collection<Point> points;
int[] values;

Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.

numberOf prefix should be used for variables representing a number of objects.

numberOfPoints, numberOfLines

Note that Sun use num prefix in the core Java packages for such variables. This is probably meant as an abbreviation of number of, but as it looks more like number it makes the variable name strange and misleading. If "number of" is the preferred phrase, numberOf prefix can be used instead of just n. num prefix must not be used.


Iterator variables should be called it

for (Iterator it = points.iterator(); i.hasNext(); )
{
  ...
} 

for (int i = 0; i < numberOfTables; i++)
{
  ...
}

Complement names must be used for complement entities.

 
get/set, add/remove, create/destroy, start/stop, insert/delete,
increment/decrement, old/new, begin/end, first/last, up/down, min/max,
next/previous, old/new, open/close, show/hide, suspend/resume, etc.

Reduce complexity by symmetry.

Abbreviations in names should be avoided.

computeAverage(); // NOT: compAvg();
ActionEvent event; // NOT: ActionEvent e;
catch (Exception exception) { // NOT: catch (Exception e) {

There are two types of words to consider. First are the common words listed in a language dictionary. These must never be abbreviated. Never write:

cmd instead of command
comp instead of compute
cp instead of copy
e instead of exception
init instead of initialize
pt instead of point
etc.

Then there are domain specific phrases that are more naturally known through their acronym or abbreviations. These phrases should be kept abbreviated. Never write:

HypertextMarkupLanguage instead of html
CentralProcessingUnit instead of cpu
PriceEarningRatio instead of pe
etc.

TODO: cu, exception changed

Negated boolean variable names must be avoided.

bool isError; // NOT: isNoError
bool isFound; // NOT: isNotFound

The problem arise when the logical not operator is used and double negative arises. It is not immediately apparent what !isNotError means.

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;

This indicates that the constants belong together, and what concept the constants represents.

An alternative to this approach is to put the constants inside an interface effectively prefixing their names with the name of the interface:

interface Color
{
  final int RED = 1;
  final int GREEN = 2;
  final int BLUE = 3;
}

=== Exception classes should be suffixed with Exception. ===
<pre>class AccessException extends Exception{...}

Exception classes are really not part of the main design of the program, and naming them like this makes them stand out relative to the other classes. This standard is followed by Sun in the basic Java library.

Default interface implementations can be prefixed by Default.

class DefaultTableCellRenderer> implements TableCellRenderer{...}

It is not uncommon to create a simplistic class implementation of an interface providing default behaviour to the interface methods. The convention of prefixing these classes by Default has been adopted by Sun for the Java library.

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() or unitManager() etc.
  {
    return instance_;
  }
}

Common practice in the Java community though not consistently followed by Sun in the JDK. The above layout is the preferred pattern.

Classes that creates instances on behalf of others (factories) can do so through method new[ClassName]

class PointFactory
{
  public Point newPoint(...)
  {
    ...
  }
}

Indicates that the instance is created by new inside the factory method and that the construct is a controlled replacement of new Point().

Consider static factory methods instead of constructors

Advantages:

  1. One advantage of static factory methods is that, unlike constructors, they have names.
  2. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
  3. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.

Disadvantages:

  1. The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
  2. A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

Follow a set of conventions when using them:

  • valueOf - Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods. Example: String.valueOf(boolean);
  • of - A concise alternative to valueOf, popularized by EnumSet.
  • getInstance - Returns an instance that is described by the parameters but cannot be said to have the same value. In the case of a singleton, getInstance takes no parameters and returns the sole instance.
  • newInstance - Like getInstance, except that newInstance guarantees that each instance returned is distinct from all others.
  • getType - Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.
  • newType - Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.
  • create[SomeSuffix] - Like newType, but may perform some special initializations on the returned objects. Example: Type.createWithDefaultResolver(...);

Public methods may delegate work to private/protected do[MethodName] methods and enclose their invocation with try/catch

public void append(..)
{
  try
  {
    doAppend(..);
  } 
  catch (Exception e)
  {
    logAppendFailedError(e);
  }
}

Sometimes the code to execute may throw exceptions which should be catched and not rethrown. Also subclasses may reimplement some behavior of the algorithm. To ensure consistency with the API one may delegate to a do[MethodName]() method and make the public method final. This way the superclass can ensure some consistency independent of actual subclasses executed.

Functions (methods returning an object) should be named after what they return and procedures (void methods) after what they do.

Increase readability. Makes it clear what the unit should do and especially all the things it is not supposed to do. This again makes it easier to keep the code clean of side effects.

List of accepted acronyms

cu
Abbreviation for Compilation Unit. Although accepted the usage of compilationUnit should be preferred over cu.
ast
Abbreviation for Abstract Syntax Tree.
jdt
Abbreviation for Java Development Tools - also used if IJavaElements are used to make clear the difference to code recommenders or ast constructs with similar names.
rec
Abbreviation for Recommenders. Typically used as prefix if objects of similar names are used in the same context. Example: jdtCu vs. recCu

Back to the top