NeXtMidas (NXM) Coding Standards

Author: Mike King (original version)

Author: Neon Ngo (updates)

1 Importance of Using a Coding Convention

Code conventions are important because throughout the life of the NeXtMidas Framework many engineers will write, contribute and maintain the code.  Everyone must conform to the Coding Convention described herein so that the time adding new functionality, fixing bugs and maintaining the code base is utilized as efficiently as possible for each and every engineering involved in the process.

Additionally, by all developers and maintainers adhering to this coding convention, NeXtMidas will be easier to use and more widely adopted as a problem-solving framework.

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

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.

2 Coding Style and File Organization

2.1 Tabbing and Indentation

The tab indent should be 2 spaces.  It is preferred that spaces are used instead of tabs.  A correctly indented piece of NeXtMidas code is:

private void refresh (int flag) {
  if (flag==0) MQ.remove("REFRESH");
  if (rescale>0) flag=Drawable.FULL;
  if (MP.status==MP.FRONT) MP.refresh(flag,null);
  if (rescale==2) rescale=0;
}

2.2 Import Statements

NeXtMidas allows the use of wildcards in import statements; fully qualified package names are optional.  The import statement should appear at the very beginning of the Java source file, before any class prologue documentation.  The final import statement should be separated from the class prologue by 2 empty lines.

2.3 Variable Declaration

Variables should be given meaningful names and thought should be given to where in the code variables are declared.  Generally, local variables should be declared at the beginning of a block of code.  Generally, variables should be declared at the beginning of the block of code in which they are required.  However, the declaration of Exceptions in a catch statements or the declaration of index variables in for loops are the two exceptions to this rule.

2.4 Use of white space

2.4.1 Blank Lines

Blank lines improve readability by setting off sections of code that are logically related.
  • Two blank lines should always be used in the following circumstances:
    • Between sections of a source file
    • Between class and interface definitions

  • One blank line should always be used in the following circumstances:
    • Between methods
    • Between logical sections inside a method to improve readability

2.4.2 Blank Spaces

Makes the individual components of the statements stand out and enhances readability.
Blank spaces should be used in the following circumstances:
  • Java reserved words should be followed by a white space.
    while (true) { // NOT: while(true){
      ...
  • Semicolons in for statements should be followed by a space character.
    for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){
      ...

3 Naming Conventions

3.1 Class and Interface Names

Class and interface names should be given names that begin with a capital letter, with subsequent words within the same name also capitalized.  Class and interface names should provide insight as to their functionality and purpose.  Examples of good names are:


Well-know acronyms (e.g., url, http, etc,...) are acceptable as components of names; however abbreviations should normally be avoided.  Examples of good class names are:

    DataFile
    ExpHelpNode
    HttpUtil

3.2 Method Names

Method names should begin with a lower-case letter, with subsequent words in the name capitalized.  The name ideally begins with an action verb, followed by an object or property.  Common properties should be accessed using get and set methods.

3.3 Variable Names

Variable names should begin with a lower-case letter, with proper capitalization in subsequent words within the name.  Examples are:

    
    testLinkPkt
    cmdline

3.4 Constants

Constants should be differentiated from variables by making them all upper case (i.e., ALL CAPS).  Individual words within a constant should be differentiated by using an underscore.  Good examples are:
DEFAULT_OPTION
HTTP_NOT_FOUND

4 Documentation and Comments

Developers shall provide documentation in the form of comments in their NeXtMidas source files.  These comments shall document the classes, methods and variables that make up the code as written.  The comments should not be verbose, but should provide enough detail so that subsequent developers and maintainers can understand the intent of the programmer by reading the comments as an adjunct to the source code.

4.1 Class Prologues

Each class shall include a brief description of the class' purpose, just after the import statements.    The comment should contain any special notes from the developer, and any assumptions made.  Where possible, these comments shall document dependencies upon other classes. Additionally, these comments should specify the original author of the code via the @ author JavaDoc tag.  The @version JavaDoc tag shall also be included in the class prologue comments, along with the $Id: nxm_coding_standards.html,v 1.1 2002/10/29 21:39:46 kingm Exp $ tag.  NeXtMidas uses the Concurrent Versioning System (CVS) for configuration management.  CVS expands this $Id: nxm_coding_standards.html,v 1.3 2002/12/09 15:58:24 millerg Exp $ as shown in the example below.  This expanded tag provides subsequent developers with critical information on the history of the changes made to the source file.  This information consists of the filename, the CVS revision number, the date and time the file was last modified, and the userid of the developer who made the last change to the file.  A typical class prologue is shown below for the Shell class:  

/**
  A class to perform shell functions.  It is responsible for initializing
  the Midas environment and presenting a terminal for command line entry
 and text based output.

  It also contains methods for parsing command lines into Args tables.

  Upon exit, it can save the current session to a file.  Upon entry, the
  session can be initialized to any saved session file.

  @author Jeff Schoen
  @version $Id: nxm_coding_standards.html,v 1.6 2011/01/31 20:23:49 ntn Exp $

*/
HTML tags are acceptable and encouraged as part of the documentation contained within the class prologue.  NeXtMidas uses the JavaDoc tool to compile code comments into a hyperlinked documentation set that is invaluable as a source of documentation that resides with and is closely coupled to the NeXtMidas source code.

4.2 Method Prologues

Method prologues are similar to Class Prologues, but they provide documentation at the method level.  The comments should utilize the JavaDoc syntax and provide information as to the function of the method.  Use of HTML comments are encouraged.  Typically Method Prologues are brief and to the point.  An example of one (along with the method it documents) is:

 /** return a type Data command line switch/parameter by name with default */
 public Data getData (String name, Data defvalue) {
   Data value = getData(name,'_');
   if (value != null) return value;
   else return defvalue;
 }

4.3 Variable Documentation

Only class and instance variables should be commented separately.  These comments should follow the JavaDoc syntax as referred to in the previous section.  Local variables should be documented as part of the inline method comments and only if its purpose is not immediately obvious.

4.4 Inline Code Comments

Inline code comments shall be utilized at a level of detail sufficient to guide the developer unfamialiar with the operations being performed by the method.  All inline code comments shall use the double-slash format

4.4.1 Block Comments

Other than described above, block comments shall be used to provide descriptions of algorithms, data structures and logic flows within a class or method.  Clock comments shall be indented to the same level of code that they are commenting.  See above sections for examples of block comments.

4.4.2 Single-line Comments

Single-line comments can be used, indented to the same level as the code it is commenting.  Any comment that cannot be contained in one line shall follow the block-comment style.  All single-line comments shall be preceded by a single blank line.  An example of a single-line comment is:
 public Data getData (String name, Data defvalue) {
   Data value = getData(name,'_');
   
   /* Return value if not null */
   if (value != null) return value;
   else return defvalue;
 }

4.4.3 Trailing-line Comments

Short comments can be included on the same line as the code they comment.  Any comments should be separated from the code by blanks sufficiently enough to visually separate it.  Multiple trailing-line comments within the same section (e.g., method) of code shall be indented to the same level.  An example of trailing line comments is:

 public Data getData (String name, Data defvalue) {
   Data value = getData(name,'_');                    /* get the value */
   if (value != null) return value;
   else return defvalue;                              /* value is null, return default */
 }

4.4.4 End-of-line Comments

End of line comments are indicated using a double-slash ("//").  These comments follow the same rules as trailing-line comments.  Specifically, they should all be indented to the same level and should be visual separate form the actual source code.  End-of-line comments shall be brief enough that they fit on the end of the line they are commenting.  If more comments are required, use a block comment.  An example of an end-of-line comment is:

 public Data getData (String name, Data defvalue) {
   Data value = getData(name,'_');                    // get the value
   if (value != null) return value;
   else return defvalue;                              // value is null, return default
 }

4.4.5 Commenting Out Line of Code

The double-slash shall be used to comment out lines of code (or partial lines, if applicable).  When commenting out entire lines of code the double-slash shall be the first 2 characters in the line.  An example of commented-out code is:

public Data getData (String name, Data defvalue) {
//   Data value = getData(name,'_');
//   if (value != null) return value;
//   else return defvalue;
   System.out.println("This method has been deprecated.");
}

5 Statement Structure Examples

5.1 Simple Statements

Each line of code shall contain only one statement. 

5.2 Compound Statements

Compound statements are those multi-line statements contained within curly braces "{<statement>}".  These statements must conform to the following rules:  

  • The enclosed statements shall be indented at least one indention level more than the compound statement.
  • The opening brace shall be at the end of the line opening the statement.
  • The closing brace shal be on a line by itself, indented at the same level as the start of the compund statement.

5.3 return Statements

Examples of acceptable return statements:

return;
return value.substring(i+1);
return value;
return Convert.o2d(obj);

5.4 if statement Variations

Examples of acceptable if statements:

5.4.1 simple if

if (vendor==null) vendor = "Unknown";
if (ref==null) ref = Shell.getMidasContext();
if (!isOpen) M.except("Could not open file: "+getURL());

5.4.2 if, else-if, else

if (op==0) dval[0]=d;
else if (op==1) dval[0]=d+1;
else if (op==2) dval[0]=d-1;
else return -1;

  

5.5 for Statements

Examples of an acceptable for statement:

for (int i=off; i<off+n; i++) a[i]=dval;

for (int i = 0; suffix != null && i < _suffices.length; ++i) {
if (suffix.equals(_suffices[i])) {
return true;
}
}

  

5.6 while Statements

Examples of acceptable while statements:

while (more()) v.addElement(get(++n));

while (i<length) {
c = buffer[++i];
buffer[j++] = c;
if (c == QUOTE) break;

5.7 do-while Statements

An example of an acceptable do-while statement:

do {
ch = pstream.read();
} while ( Character.isWhitespace( (char)ch ) );

5.8 switch Statements

Examples of acceptable switch statements:

 switch (key) {
case 'S': name = "Scalar"; break;
case 'C': name = "Complex"; break;
case 'V': name = "Vector"; break;
case 'Q': name = "Quad"; break;
case 'M': name = "Matrix"; break;
case 'X': name = "10 *"; break;
case 'T': name = "TransMatrix"; break;
case 'N': name = "Non"; break;
default: name = "Undefined"; break;
}

switch (type) {
case AZIM: r.a11=ca; r.a12=-sa; r.a21=sa; r.a22=ca; break;
case YAW: r.a11=ca; r.a12=-sa; r.a21=sa; r.a22=ca; break;
case ELEV: r.a11=ca; r.a13=-sa; r.a31=sa; r.a33=ca; break;
case PITCH: r.a11=ca; r.a13=sa; r.a31=-sa; r.a33=ca; break;
case ROLL: r.a22=ca; r.a23=-sa; r.a32=sa; r.a33=ca; break;
}

5.9 try-catch Statements

Examples of acceptable try-catch statements:

 try {
PrivilegeManager.enablePrivilege("UniversalLinkAccess");
setPriv (PRIV_QUERYOS);
} catch (RuntimeException e) { System.out.println("Shell: "+e); }


try {
String key = keys[i];
if (obj instanceof Table) object = ((Table)obj).getKey(key);
else if (obj instanceof KeyVector) object = ((KeyVector)obj).getKey(key);
else if (obj instanceof Hashtable) object = ((Hashtable)obj).get(key);
else if (gets[i]!=null) object = gets[i].invoke(obj,null);
else object = null;
}
catch (Exception e) { }

5.10 ternary Statements

Ternary statements are NOT RECOMMENDED in NeXtMidas, but judicious use is ok.


6 References