myWMS Style Guide Page 1/15 myWMS Style Guide by Heinz W. Huber Text Editor | Version Control | Documentation | Javadoc | Source Code | Java | HTML | JSP | Proposals This document gives a small introduction in how to participate in the myWMS project. As more than a few developers are working simultaneously at different places on the world, it is very important to have a similar view to all sources. Text Editor On principle, sources can be edited with any text editor. However, the following rules should apply: A tab equals 2 spaces. The unix convention (\n) for line breaks must apply. This is especially important for Windows editors. (There are different rules for working with WinCVS, which may perform automatic conversion.) Start Version Control By installing a CVS repository, it is assured that all developers are working with the same version of source code and document files. The current state is always in the repository. WinCVS for windows and the corresponding command line tools for Linux/Unix are used. Before starting work with a new task, an update of the local archive has to be performed. Only sources which can be compiled without error and which do not disobey the integrity of the whole archive may be committed. After committing an archive, it should be checked out to a new (clean) directory to check if it can be compiled without error. (One of the most frequent problems with CVS repositories are not registered - and hence missing - source files.) When committing changes, short comments should be inserted that specify the changed version. Examples: o "New method xxx() added and integrated" o "New source file de.fhg.iml.mywms.tools.zzz added" Documentation Software documentation will be integrated in the sources on term of Javadoc. On agreement, an updated documentation will be generated and published in HTML via Intra- and Internet. User documentation will be created on demand. The GUI team is responsible for this. It should always be possible to invoke the proper documentation within the current context. (Opening an HTML page - e.g. in a browser in kiosk mode - will be adequate.) Start © 2002 Fraunhofer IML myWMS Style Guide Page 2/15 Javadoc All sources are commented according to the Javadoc convention. In essence: At the top of each class, its purpose should be described. Also, the author of the class must be mentioned here. The author's name should contain a hyperlink to the corresponding myWMS web page: @author <A HREF="http://www.mywms.de/inside/authors.html">My Name</A> @version $Revision: x.x $ provided by $Author: name $ Thus the author of a Java class can directly be accessed. The string following @version will be updated by CVS and helps to associate the documentation with the proper source code version. @author of a class is 1. the designer of the class and 2. the programmer responsible for it. At the top of each method a short comment describes what happens in this method. For interface methods, class comments and method comments are mandatory. Especially the @param and @return tags must be specified here. Example: /** This class is an example for Javadoc. * That's its only purpose. * * @author Kalle Blomquist * @version $Revision: 1.23 $ provided by $Author: Kalle Blomquist $ */ class Test { /** Saves the number of elements. */ private int count; /** Returns the number of elements. * @return Number of elements */ public int getCount() { } /** Sets the number of elements. * @param Number of elements */ public void setCount (int count) { this.count = count; } } In this example, @return and @param are not too ingenious, but entirely legal. @return and @param should always be used for more complex methods or e.g. if the signature contains a number of unmeaning data types: public int calculate (int i, double d, String s, double dd); Without @param, the parameters will be hard to collate. An overview of usable tags can be found internally here or externally here. Start © 2002 Fraunhofer IML myWMS Style Guide Page 3/15 Source Code English language is used for code generation and comments. Start Java Source Files | Indentation | Comments | Declarations | Statements | White Space | Naming Conventions | Programming Practices | Further Conventions Source Files Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file. Each class has at least one owner (author). Only the owner may change the class. Exceptions only according to prior agreement with the author. Accordingly, the owner of a class is responsible for its function. Java source files have the following ordering: A beginning comment that lists the class name and date. Forte4J will create this comment automatically. The package statement. import statements. Class and interface declarations. These contain: o Static variables (public, protected, package level, private) o Instance variables (public, protected, package level, private) o Constructors o Methods. These methods should be grouped by functionality rather than by scope or accessibility. Java Contents Indentation Avoid lines longer than 72 characters, since they're not handled well by many terminals and tools. When an expression will not fit on a single line, break it according to these general principles: Break after a comma. Break before an operator. Prefer higher-level breaks to lower-level breaks. Align the new line with the beginning of the expression at the same level on the previous line. © 2002 Fraunhofer IML myWMS Style Guide Page 4/15 Examples: someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3)); Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level. longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID! longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 2 tabs (4 spaces) instead. someMethod(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } private static synchronized horkingLongMethodName(int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } Blocks (in braces) will always be indented by 2 spaces (1 tab). A blank space is placed before the open brace "{": for (int i = 0; i < 10; i++) { system.out.println("i=" + i); } Nested conditions for conditional statements which extend over multiple lines should be indented like in this example. Here, the open brace "{" of the statement block will be placed in a separate line: if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); } © 2002 Fraunhofer IML myWMS Style Guide Page 5/15 Here are three acceptable ways to format ternary expressions: alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; alpha = (aLongBooleanExpression) ? beta : gamma; Java Contents Comments Java programs can have three kinds of comments: Comments which will later be part of the documentation should begin with /** and end with */. Every comment line starts with *. These doc comments can be extracted to HTML files using the Javadoc tool. Javadoc comments should be written as complete sentences. Comments in the code should begin with // and need not be written as complete sentences. They should be placed above the line of code they refer to and be preceded by a blank line. Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. However, the total line length including comments should not exceed 80 characters (see Indentation). The delimiters /* ... */ should not be used for comments, but rather for commenting out parts of the code during test. To improve readability, long source codes should be separated into the sections Static, Attributes, Constructors and Methods. Methods which implement an interface should be grouped into one section for each interface. Example: // -----------------------------------------------------------------// Methods implementing interface ComDispatcher // -----------------------------------------------------------------Java Contents © 2002 Fraunhofer IML myWMS Style Guide Page 6/15 Declarations Variables will always be declared at the beginning of the block in which they are used. Counter variables etc. should be declared at the beginning of the block as well. One declaration per line is recommended since it encourages commenting. Do not put different types on the same line. Example: int foo, fooarray[]; // WRONG! Variables should be initialized in the declaration. However, the first assignment should not take place before a variable is used for the first time. Example: public Object assign() { int i; // Declaration without initialisation Object o = null; // Initialisation because null is possible in return for (i = 0; i < 10; i++) { // Assignment to i - indispensable if (d.isGood()) { o = d; // Assignment to o, overwrites null in case of isGood() break; } } return o; } Local Declarations The declaration of local variables inside an inner block should be avoided. If local declarations are indispensable, they should not hide declarations at higher levels, e.g. by using the same variable name: int count; ... myMethod() { if (condition) { int count = 0; ... } ... } // AVOID! Class and Interface Declarations When coding Java classes and interfaces, the following formatting rules should be followed: extends and implements declarations are each placed in a separate line below the class/interface name. These lines are indented 1 tab (2 spaces). The open brace "{" of the class body starts a line by itself indented to match the begin of the class declaration. The closing brace "}" of the class body starts a line by itself indented to match the begin of the class declaration. © 2002 Fraunhofer IML myWMS Style Guide Page 7/15 Methods When coding methods, the following formatting rules should be followed: No space between a method name and the parenthesis "(" starting its parameter list. After empty or short parameter lists which fit in one line, the open brace "{" follows the closing paranthesis ")" after a blank. Long parameter lists are broken in multiple lines (see Indentation). In this case, the open brace "{" starts a line by itself indented to match its corresponding opening statement. When methods explicitly throw an exception, the throws statement is placed in a line by itself after the parameter list, indented 1 tab. The open brace "{" starts a line by itself indented to match its corresponding opening statement. Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{". Methods are separated by a blank line. Examples: public interface Criterion extends Serializable { } public class MyWMSException extends Exception implements Serializable { /** Creates a new WarehouseException. */ public MyWMSException(String message) { super(message); } } class Sample extends Object { int ivar1; int ivar2; Sample(int i, int j) { ivar1 = i; ivar2 = j; } void aSampleMethodWithVeryLongParameterList(int firstLongParameterName, int secondLongParameterName, int anotherLongParameterName) { ... } © 2002 Fraunhofer IML myWMS Style Guide Page 8/15 public void setCarriageId(int carriageId) throws MyWMSException { this.carriageId = carriageId; ... } int emptyMethod() {} ... } Java Contents Statements Simple Statements Each line should contain at most one statement. Compound Statements A block will always follow after if, else, for, while etc., even for one single instruction: if (b) { b = !b; } return Statements A return statement with a value should not use parentheses unless they make the return value more obvious in some way. Example: return; return myDisk.size(); return (size ? size : defaultSize); if, if-else, if-else if-else Statements The if-else class of statements should have the following form: if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; } else if (condition) { statements; } else { statements; } © 2002 Fraunhofer IML myWMS Style Guide Page 9/15 for Statements A for statement should have the following form: for (initialization; condition; update) { statements; } An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form: for (initialization; condition; update); When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. while Statements A while statement should have the following form: while (condition) { statements; } An empty while statement should have the following form: while (condition); do-while Statements A do-while statement should have the following form: do { statements; } while (condition); switch Statements A switch statement should have the following form: switch (condition) { case ABC: statements; // no break! case DEF: statements; break; case XYZ: statements; break; default: statements; break; } Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the // no break! comment. © 2002 Fraunhofer IML myWMS Style Guide Page 10/15 Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added. try-catch Statements A try-catch statement should have the following format: try { statements; } catch (ExceptionClass exc) { statements; } Java Contents White Space Blank Lines Blank lines improve readability by setting off sections of code that are logically related. One blank line should always be used in the following circumstances: Between methods. Between the local variables in a method and its first statement. Before a block or single-line comment. Between logical sections inside a method to improve readability. Blank Spaces Blank spaces should be used in the following circumstances: A keyword followed by a parenthesis should be separated by a space. Note that a blank space should not be used between a method name and its opening parenthesis (see Declarations). This helps to distinguish keywords from method calls. A blank space should appear after commas in argument lists. All binary operators except "." should be separated from their operands by spaces. Blank spaces should never separate unary operators ("-", "++", "--") from their operands. Example: a += c + d; a = (a + b) / (c * d); while (d++ < s) { n++; } printSize("size is " + foo + "\n"); The expressions in a for statement should be separated by blank spaces. Example: for (expr1; expr2; expr3) { ... Casts should be followed by a blank space. Examples: myMethod((byte) aNum, (Object) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1); Java Contents © 2002 Fraunhofer IML myWMS Style Guide Page 11/15 Naming Conventions Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier - for example, whether it's a constant, package, or class - which can be helpful in understanding the code. The following rules should apply: Composed names like e.g. getActualName() contain upper case letters at significant positions - however, getPrename() will not become getPreName()! The names of classes, packages, attributes and methods should neither contain underlines nor "$" characters. Package names are written in lowercase letters, e.g. de.mywms.wms.kernel Interface and Class names begin with a capital letter. Interface names end with the word Interface to help to distinguish them from class names. The name of a Method should describe its action. The name begins with a lowercase letter: getArticleFromCarriage() Variable names begin with a lowercase letter. The names of variables declared Constants should be all uppercase with words separated by underscores: static final int MIN_WIDTH = 4; Java Contents Programming Practices Class Names The first statement in each classes body is the declaration of the string CLASSNAME in the Static section. This string will be used for each log output to identify the class unambiguously. // -----------------------------------------------------------------// Static // -----------------------------------------------------------------private static final String CLASSNAME = SampleClass.class.getName(); All important modules and interfaces should log their actual revision with the first log output. The revision number will be inserted by CVS automatically with each update of the source code: static { LogSingleton.logInformation(CLASSNAME, "myWMS Modul", "$Revision: x.x $"); } Access Attributes should be declared private and be encapsulated by get- and set-methods. Set-methods will always contain an assertion. Calling a set-method with an invalid value will make it throw an exception. When attributes have get- and set-methods, they are implicit properties. Boolean attributes have is-methods in place of get-methods. Example: class Test { © 2002 Fraunhofer IML myWMS Style Guide Page 12/15 private String name; private boolean loud; public String getName() { return name; } public void setName(String name) { // assertion if (name == null) { throw new TestPackageException("name must not be null"); } // assignment this.name = name; } public boolean isLoud() { return loud; } public void setLoud(boolean loud) { this.loud = loud; } } Class Constants Variables declared class constants should always be declared public to allow direct access. Variable Assignments Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: fooBar.fChar = barFoo.lchar = 'c'; // AVOID! Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example: d = (a = b + c) + r; // AVOID! should be written as a = b + c; d = a + r; Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others you shouldn't assume that other programmers know precedence as well as you do. if (a == b && c == d) if ((a == b) && (c == d)) // AVOID! // RIGHT! Java Contents © 2002 Fraunhofer IML myWMS Style Guide Page 13/15 Further Conventions Exceptions If exceptions of a called method should be evaluated, the thrown exception must be caught explicitly before any other possible exceptions: try { Statements; } catch (RuntimeException rte) { Statements; } catch (ExceptionClass exc) { Statements; } Complex Data Types Complex data types like a java.util.Vector should not be returned directly since no type verification takes place - a vector can contain objects of any type. These data types should be encapsulated by the BusinessObject using the necessary methods. Example: class Test2 { private Vector names = new Vector(); public String getName(int i) { // assertion if (i < 0 || i > names.size()) { throw new TestPackageException("names: index out of range"); } return (String) names.elementAt(i); } public void addName(String name) { // assertion if (name == null) { throw new TestPackageException("name must not be null"); } names.addElement(name); } public void setName(String name, int i) { // assertion if (name == null) { throw new TestPackageException("name must not be null"); } if (i < 0 || i > names.size()) { throw new TestPackageException("names: index out of range"); } names.setElementAt(name, i); } public void removeName (int i) { © 2002 Fraunhofer IML myWMS Style Guide Page 14/15 // assertion if (i < 0 || i > names.size()) { throw new TestPackageException("names: index out of range"); } names.removeElementAt(i); } public int getNameCount() { names.size(); } } Lists Lists should be returned as typified arrays. However, performance may require compromises here. Java Contents HTML HTML-Documents should be dissected by scope. Example: <TABLE> <TR> <TH>Header1</TH> <TH>Header2</TH> </TR> <TR> <TD> <P>These are the table cell data.<BR> In this case we have multi row table cells.</P> </TD> </TR> </TABLE> Opened tags should always be closed, even if it is not demanded by the HTML standard like e.g. for <P> or <LI>. Upper or lower case spelling for tags should be applied consistently throughout a document, preferably upper case for all tags. HTML documents should be tested with Internet Explorer and Netscape Navigator. HTML documents should be passed by code checkers. Errors will be noticed and analyzed here that a practice test might not unveil. Format specifications should always be based on style sheets. The intention is to create applications that can easily be readjusted to a different corporate design. The author of each HTML document should be mentioned in its head, using the proper meta tag: <META NAME="author" CONTENT="Kalle Blomquist"> WYSIWYG editors that "beautify" the source code (e.g. Netscape Composer) should not be used. CVS will not be able to compare the versions correctly; in addition, the readability will decline. Start © 2002 Fraunhofer IML myWMS Style Guide Page 15/15 JSP For the Java part of JSP documents, the Java Style Guide applies. For the HTML part, the HTML Style Guide applies. Declarations should be placed at the very top of each JSP document. Start Proposals Do you have further proposals concerning the Style Guide? Please mail info@mywms.de! Start Last update of this document: 29/06/2016 01:28:00 © 2002 Fraunhofer IML