Since many programmers work on the same source files, it is good practice to define a common standard of formatting rules and other conventions to make the code easier to read and understand for everyone. This document describes general conventions for writing Java source code including JavaDoc. The conventions should be used for all Java code that is implemented by Intershop.
For Intershop Studio there exists a predefined formatter configuration:
Change your editor settings as follows:
Use American English as language for all comments, classes, interfaces, methods and variables. Write all comments in American English .
Use only ASCII characters in Java source files. This means e.g. no German umlauts like ä, ö, ü or no ß.
Code blocks (within curly brackets) always begin and end in a new line.
if (condition) { doSomeStuff(); }
if (condition) {doSomeStuff();}
To avoid deep nestings, use early returns, continue and break.
public void method(Object a, Object b) { if (a == null) { return; } if (b == null) { return; } doSomething(); }
public void method(Object a, Object b) { if (a != null) { if (b != null) { doSomething(); } } }
Please observe the following rules when declaring Java methods:
public, protected
or private
).this.
keyword when possible.public UserGroup getUserGroup(Domain domain, String id); public void setUserGroupName(UserGroup userGroup, String name);
Add each class you want to import in a separate single import statement. Do not import a whole package. Exceptions are JDK classes.
import foo.bar.a; import foo.bar.c;
import foo.bar.*;
The if and else branch should always be put into curly brackets, e.g.:
if (condition) { doSomeStuff(); } else { doSomeOtherStuff(); }
if (condition) doSomeStuff();
Switch statements should look as follows:
switch (condition) { case ABC: statements; case DEF: statements; break; case XYZ: { int x=1; statements; } break; default: statements; break; }
If the cases perform only trivial actions, line breaks can be omitted.
switch (x) { case A: return "A"; case B: return "B"; case C: return "C"; default: return "N/A"; }
A keyword followed by a parenthesis should be separated by a space. Example:
while (i > 0) { } for (int i = 0; i < 100; i++) { } if (a) { } else if (b) { }
Please mind the following notes:
All binary operators except "." 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.
a += c + d; a = (a + b) / (c * d); while (n < 5) { n++; } printSize("Size is " + foo + ".\n");
Casts should not be followed by a blank space.
myMethod((byte)aNum, (Object)x); myMethod((int)(cp + 5), ((int)(i + 3)) + 1);
When an expression does not fit on a single line, break it according to these general principles:
someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3));
Below are two examples of breaking an arithmetic expression. The first one is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID
The following examples illustrate indenting method declarations. The first example 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.
// Conventional indentation someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { } // Indent 8 spaces to avoid very deep indents private static synchronized workingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) throws Exception { }
Examples of breaking an if statement:
if ( (condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); }
Here are three acceptable ways to format ternary expressions:
alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma;
There are some general rules:
/* * Copyright (C) Intershop Communications AG - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited. * The content is proprietary and confidential. * Intershop Communication AG, Intershop Tower, 07740 Jena, Germany, August 2017 */
Class and interface names start with an uppercase letter: FirstLetterOfAllWordsCapitalized
.
public class Customer { }
public class SavingsAccount { }
The following abbreviations are used as suffix of class names:
Suffix | Description |
---|---|
*Impl | Implementation for a default implementation of an interface |
*Mgr | Manager |
*Ctnr | Container |
*Ctlr | Controller |
*Ctx | Context |
Please think about better names as Manager, Container, Controller, retrieve main name from business domain model. Think about the responsibility or core competence of the class.
Method names start with an active verb describing some action and a lower-case first letter: firstLetterInLowerCase
.
openFile()
createAccount()
When possible, use fully qualified names. If they are too long, use an abbreviation which consists of the first letters in upper case.
* getName(); // complete word * getLastName(); // multiple complete words, each with upper case first letter * getSKU(); // abbreviation for "stock keeping unit", so only use the first letters in upper case * getID(); // abbreviation for "identifier", so only use the first letters in upper case * getRadar(); // short for "radio detection and ranging", but it is not an abbreviation, it is an acronym that is pronounced as a word, therefore treat it like a complete word
Please mind the following rules for naming customary types of methods:
getFirstName()
getWarpSpeed()
java.lang.Boolean
as a return value. Examples are:isString()
isPersistent()
canPrint()
hasDepends()
setFirstName()
setWarpSpeed()
setPriceForCone()
addUser(User user);
removeUser(User user);
Collection<User> getAllUsers();
null.
If there are no elements, an empty collection must be returned .
createProduct();
deleteProduct();
Package names are formed from a reverse Internet domain name.
com.intershop.*
The following package names are used for Intershop platform and solution development.
com.intershop.adapter.*
- for all Intershop 7 adapter components.com.intershop.application.*
- for all Intershop 7 applications.com.intershop.appsuite.*
- for all Intershop 7 application suites.com.intershop.beehive.*
- for all Intershop 7 platform components (deprecated, do not use anymore for new code).com.intershop.component.*
- for all Intershop 7 business components.com.intershop.init.*
- for all Intershop 7 initialization components.com.intershop.platform.*
- for all Intershop 7 platform components.com.intershop.tool.*
- for all Intershop 7 tools.com.intershop.ui.*
- for all Intershop 7 user interface libraries.com.intershop.<solution name>.*
- for all Intershop business solutions.For customer projects, the prefix for the Java packages would not be com.intershop.*
, but some customer-specific prefix.
The local variable names i, j, k, l
and so on should be used as loop counters.
The first letter should be in lower case. Common name suffixes include "ID" and "UUID":
customer value domainID firstName warpSpeed customerAddress numberOfCustomers
Local variables should not be named similar to instance variables in the same scope.
Usually it is recommended to use different names for parameters and member names. Deviating from this , if the code includes the "set" of the member name then the meaning of the parameter is the "new" "member". In that case it is recommended to use the same name.
public class Person { private String name; public Person(String name) { this.name = name; } public void setName(String name) { this.name = name; } }
Constants should be given a name in uppercase and with underscores to separate words. A constant must also be declared as a "static final" class variable. Examples are:
MINIMUM_PAYMENT
STATE_TAX
If there is a group of constants belonging together, keep the changing part at the end:
AUCTION_STATE_ONLINE
AUCTION_STATE_OFFLINE
Single line comments can be used to document the programming logic in the Java code, to structure sections of code or to document local variables. Write as much comments as possible in order to make it easy for other developers to understand your code some time later.
Intershop Studio can automatically generate task entries that are clickable by simply marking a code place with a "TODO" tag.
// comments // TODO comment here what to do
C-Style can be used for temporary changes or for comments that should not appear in the JavaDoc.
/* not for Java documentation purpose */
When documenting code artifacts such as classes and interfaces, methods, instances and class variables, write JavaDoc comments whenever possible and applicable:
/** * Here is the documentation that will be processed by JavaDoc. */
JavaDoc supports certain tags in the comment to mark certain types of information. This information should be provided whenever possible.
java.rmi.RemoteException
can be omitted.The JavaDoc tags should be used in the following order within JavaDoc documentation sections of classes, methods and attributes.
@See tags are written in the following manner:
@see #field @see #Constructor(Type, Type...) @see #Constructor(Type id, Type id...) @see #method(Type, Type,...) @see #method(Type id, Type, id...) @see Class @see Class#field @see Class#Constructor(Type, Type...) @see Class#Constructor(Type id, Type id) @see Class#method(Type, Type,...) @see Class#method(Type id, Type id,...) @see package.Class @see package.Class#field @see package.Class#Constructor(Type, Type...) @see package.Class#Constructor(Type id, Type id) @see package.Class#method(Type, Type,...) @see package.Class#method(Type id, Type, id) @see package
JavaDoc can contain HTML tags, some useful are: <p>, <br>, <pre>, <code>, <ul>, <li>
...
Write your documentation text always as full sentences including the description of parameters, return values and exceptions. For constant values of a discrete value document the actual value.
/** * Type code for a RequisitionAWFDefinition for department approval. * The value is '<code>1</code>'. */ public static int DEFINITIONTYPE_DEPARTMENT = 1;
Beside the standard JavaDoc annotations there are a number of Intershop-specific annotations that are used by our Code Generator. Using the annotations, the merging process of generated code and manually enhanced code can be controlled.
/** * First Sentence gives a short description about the API. * ...here follows detailed documentation... * * @author John Doe * @see BaseClassName */ class ClassName extends BaseClassName { }
/** * Description of the function of the method. * * @param paramName description * @return description * @exception nameOfException circumstances which cause the exception * @see referenceToOtherStuff */ public returnType doStuff(parameter) throws XYZException { }
/** * The current number of elements. * Must be non-negative, and less than or equal to capacity. */ protected int count;
Some classes allow the use of Java dependency injection. At which places injection can be used is beyond the scope of this document, but some general rules apply:
javax.inject.*
API whenever possible, avoid using implementor-specific classes and annotationsLog Levels are describe at Concept - Logging.
Error log entries should always contain an exception, so not just the information is logged, but also the stack trace, in which context the error occurs.
Information should be logged only once. This implies, that exceptions are not thrown and logged at the same time. Put much as possible information to the log, which are not part of parameters of the called function.
In case a new exception needs to be thrown, the original exception needs to be added.
public any doStuff(parameter) { try { otherParameter = f(parameter); abc(otherParameter); } catch (XYZException e) { Logger.error("doStuff failed", e); throw e; } }
public any doStuff(parameter) { try { otherParameter = f(parameter); abc(otherParameter); } catch (XYZException e) { Logger.error("executing fails with parameter: "+ parameter, e); } }
public any doStuff(parameter) { try { otherParameter = f(parameter); abc(otherParameter); } catch (XYZException e) { throw new ABCException("executing fails with parameter: "+ parameter, e); } }