Difference between revisions of "PKI Java Coding Style"

From Dogtag
Jump to: navigation, search
 
 
(84 intermediate revisions by 2 users not shown)
Line 1: Line 1:
== Introduction ==
+
== Why Have A Coding Style? ==
  
This document describes the Java coding style standards for Fedora Certificate System.
+
=== For easier maintenance ===
It contains certificate server specific additional comment that are in ''italics''.
 
  
== General Coding Rules ==
+
If you're merging changes from a patch it's much easier if everyone is using the same coding style.  This isn't the reality for a lot of our code, but we're trying to get to the point where most of it uses the same style.
  
=== Naming Conventions ===
+
=== Improved readability ===
  
'''Package Names'''
+
Remember, code isn't just for compilers, it's for people, too.  If it wasn't for people, we would all be programming in assembly.  Coding style and consistency mean that if you go from one part of the code to another you don't spend time having to re-adjust from one style to another.  Blocks are consistent and readable and the flow of the code is apparent.  Coding style adds value for people who have to read your code after you've been hit by a bus.  Remember that.
  
* Package names should be single lowercase words.
+
== General Rules ==
* ''Certificate server specific packages should be sub-packages of "com.netscape.certsrv".''
 
  
''Interface Names''
+
* All source files should include a copy of the license.
 +
* Space after keywords
 +
* Curly braces on new line following a class.
 +
* Curly braces on new line following a method.
 +
* Curly braces on same line as if/while/switch.
 +
* All code should be peer reviewed before being checked in.
  
* ''Interface names should begin with "I". For example, IConfigStore''
+
=== Naming Conventions ===
  
''Exception Names''
+
'''Package Names'''
* ''Exception names should begin with "E". For example, ECMSException''
 
* ''Exceptions should have their own hierarchy in each certificate server subsystem. (This implies that each subsystem should define a new exception that extends the base exception ECMSException.)''
 
  
'''Class Names'''
+
* Package names should be single lowercase words.
 +
* Dogtag Certificate System-specific packages should be sub-packages of "com.netscape.certsrv".
  
<UL>
+
'''Interface Names'''
<LI>
 
Concrete classes should use natural descriptive names, begin with a capital,
 
and have mixed case:&nbsp; <I>FooBarReader</I></LI>
 
  
<LI>
+
* Interface names should begin with "I". For example, IConfigStore.
<I>Abstract class should begin with "A". For example, ABaseClass</I></LI>
 
</UL>
 
<B><FONT SIZE=+1>Member Function Names</FONT></B>
 
<UL>
 
<LI>
 
Method ("member function") names should begin with a lowercase letter with
 
each subsequent new word in uppercase, and subsequent letters in each word
 
in lower case.</LI>
 
  
<LI>
+
'''Exception Names'''
Methods for debug-only implementation should begin <STRIKE>with "mortMortMort".
 
(Alternatively they can begin with the word </STRIKE>"debug"<STRIKE>)</STRIKE>.</LI>
 
  
<LI>
+
* Exceptions should have their own hierarchy in each certificate server subsystem. (This implies that each subsystem should define a new exception that extends the base exception ECSException).
Static methods should begin with a capital letter with each subsequent
 
new word in uppercase, and subsequent letters in each word in lower case.</LI>
 
</UL>
 
  
<DIR>
+
'''Class Names'''
<PRE><I><TT>example</TT></I></PRE>
 
 
 
<DIR><TT><FONT SIZE=-1>public class MyClass</FONT></TT>
 
<BR><TT><FONT SIZE=-1>{</FONT></TT>
 
<BR><TT><FONT SIZE=-1>&nbsp;&nbsp;&nbsp; void doSomethingNeat(int aValue);</FONT></TT>
 
<BR><TT><FONT SIZE=-1>&nbsp;&nbsp;&nbsp; void debugDumpToScreen();</FONT></TT>
 
<BR><TT><FONT SIZE=-1>&nbsp;&nbsp;&nbsp; static void SomeClassMethod(int
 
aValue);</FONT></TT>
 
<BR><TT><FONT SIZE=-1>};</FONT></TT></DIR>
 
</DIR>
 
 
 
<B><FONT SIZE=+1>Component Factory Names</FONT></B>
 
 
 
<P>A component factory is a public class that implements only static methods.
 
These static methods are "Factory functions" or "component constructors".&nbsp;
 
Factory class names should include the word "Factory".&nbsp; Factory method
 
names should start with the word "Make."&nbsp; For example,
 
<UL><TT><FONT SIZE=-1>public class WidgetFactory</FONT></TT>
 
<BR><TT><FONT SIZE=-1>{</FONT></TT>
 
<BR><TT><FONT SIZE=-1>&nbsp;&nbsp;&nbsp; static Button MakeButton(int aButtonType);</FONT></TT>
 
 
 
<BR><TT><FONT SIZE=-1>&nbsp;&nbsp;&nbsp; static ListBox MakeListBox();</FONT></TT>
 
<BR><TT><FONT SIZE=-1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
};</FONT></TT></UL>
 
<B><FONT SIZE=+1>Function Naming Patterns</FONT></B>
 
<UL>
 
<LI>
 
Getters and setters should begin with "get" / "set" and return the approriate
 
object type.</LI>
 
 
 
<LI>
 
Boolean getters should use "is" or "can" as a prefix, such as "isUndoable()"
 
rather than "getUndoable()"</LI>
 
</UL>
 
 
 
<B><I><FONT SIZE=+1>Constants</FONT></I></B>
 
<UL>
 
<LI>
 
<I>Constants will use all uppercase and will have words separated by underscores.</I></LI>
 
</UL>
 
<B><I><FONT SIZE=+1>General Varibles and Paramters Names</FONT></I></B>
 
<UL>
 
<LI>
 
<I>Variables and parameters will begin with a lower case, and have mixed
 
case. For example, fooBarReader</I></LI>
 
 
 
<LI>
 
<I>Member variable should begin with "m". For example, mMemberVariable.</I></LI>
 
 
 
</UL>
 
<A NAME="Commenting Code"></A><B><FONT SIZE=+2>Commenting Code</FONT></B>
 
 
 
<P>All interfaces and public classes should have JavaDoc comments. See
 
the <A HREF="Javadoc_Basics.html">JavaDoc Basics document.</A>
 
<BR>&nbsp;
 
<BR>&nbsp;
 
<TABLE BORDER=0 COLS=1 WIDTH="100%" BGCOLOR="#CCFFFF" >
 
<TR>
 
<TD><A NAME="General Coding"></A><FONT SIZE=+3>General Coding Guidelines</FONT>&nbsp;</TD>
 
</TR>
 
</TABLE>
 
<B><FONT SIZE=+1>Java Grammar</FONT></B>
 
 
 
<UL>&nbsp;
 
<LI>
 
Wherever appropriate, avoid code that embeds many operations in a single
 
line.&nbsp; For example, avoid:&nbsp;<TT><FONT SIZE=+1> someObject.doThis(i++,
 
otherObject.someField.doThat(), x?y:z)</FONT></TT>.&nbsp; This kind of
 
code is error prone, difficults to decipher, and hard to maintain.</LI>
 
</UL>
 
<B><FONT SIZE=+1>Debugging</FONT></B>
 
 
 
<P>1. First and foremost, go read Writing Solid Code. Now go back and reread
 
the java programming language reference documentation to refresh you memory
 
on the precedence order of operators.
 
 
 
<P>2. Now go read the <A HREF="ErrorHandling.html">Abnormal Condition Handling</A>
 
 
 
document.
 
 
 
<P>3. You can never do enough coverage testing. Make sure <I>every</I>
 
path of execution through your code has been thoroughly tested. Here�s
 
a neat idea: try actually stepping through each line! While you're hard
 
at work testing your code, be sure to throw invalid inputs at every public
 
interface you provide. The last thing we want to do is crash because <I>your</I>
 
routine didn't handle invalid inputs from <I>ours.</I> Never <B><I>ever</I>
 
</B>break the build (except by prior agreement of all members of the team,
 
for a specified purpose and duration.)
 
 
 
<P>4. Want to know the secret to fast code? Calculate those comparison
 
values once: reuse them often. Avoid global variables too, since they can
 
wreak havoc with the pre-fetch instruction queue.
 
<H1>
 
<FONT SIZE=+1>Orthodox Cannonical Form</FONT></H1>
 
 
 
Don�t forget to adhere to our Orthodox Canonical Form. This is a template
 
that, when followed, guarantees that you have all the default methods your
 
class needs to be a good java citizen. See <I>Standards.java</I> on the
 
magellan site.
 
 
 
<P>It is our policy to produce code that can test itself to the greatest
 
extent possible. To that end, we encourage the use of three debugging techniques:
 
asserts, pre/post conditions and self testing methods.
 
<UL>
 
<H2>
 
<I><FONT SIZE=+1>1. Asserts</FONT></I></H2>
 
It is highly recommended that assert methods (warnings/errors) be used
 
to aid in debugging, especially to verify assumptions made in code. This
 
will be the technique used for reporting run-time errors and warnings.&nbsp;
 
There is a full suite of assert technology provided in mg.util.Assert.java.
 
 
 
<P>We've worked through many of these issues, and they can be found in
 
the Abnormal Condition Handling document on the Magellan site.
 
<H2>
 
<I><FONT SIZE=+1>2. Pre and Post Conditions</FONT></I></H2>
 
In order to bulletproof your code, you should use asserts to test all boundary
 
conditions. You aren't doing anyone any favors by "defensive" programming
 
practices that allow clients of your code to make improper calls.&nbsp;
 
 
 
In other words, it is better to blow up (in debug builds) if you are given
 
bad data than to try to "fix" the data and therefore hide bugs.
 
<DIR><I>example</I>
 
<DIR>
 
<DIR><I>&nbsp;</I></DIR>
 
</DIR>
 
  
<DD>
+
* Concrete classes should use natural descriptive names, begin with a capital, and have mixed case. For example, FooBarReader.
<FONT SIZE=-2>String copyString(String aOtherString)</FONT></DD>
 
  
<DD>
+
'''Member Function Names'''
<FONT SIZE=-2>{</FONT></DD>
 
  
<DD>
+
* Method ("member function") names should begin with a lowercase letter with each subsequent new word in uppercase, and subsequent letters in each word in lower case.
<FONT SIZE=-2>&nbsp;&nbsp;&nbsp; Assert.PreCondition(NULL != aOtherStr,
+
* Methods for debug-only implementations should begin with "debug".
"Null string given");</FONT></DD>
+
* Static methods should begin with a capital letter with each subsequent new word in uppercase, and subsequent letters in each word in lower case.
  
<DD>
+
    public class MyClass
<FONT SIZE=-2>&nbsp;&nbsp;&nbsp; ...</FONT></DD>
+
    {
 +
        void doSomethingNeat(int aValue);
 +
        void debugDumpToScreen();
 +
        static void SomeClassMethod(int aValue);
 +
    }
  
<DD>
+
'''Component Factory Names'''
<FONT SIZE=-2>&nbsp;&nbsp;&nbsp; Assert.PostCondition(fSelfString.length()
 
>=aOtherString.length(), "lengths don't match after copy.");</FONT></DD>
 
  
<DD>
+
A component factory is a public class that implements only static methods.  These static methods are "Factory functions" or "component constructors".  Factory class names should include the word "Factory".  Factory method names should start with the word "Make." For example:
<FONT SIZE=-2>}</FONT></DD>
 
  
<DIR><FONT SIZE=-1>&nbsp;</FONT></DIR>
+
    public class WidgetFactory
</DIR>
+
    {
 +
        static Button MakeButton(int aButtonType);
 +
        static ListBox MakeListBox();
 +
    }
  
We do not want debug code to be included into release builds. Therefore,
+
'''Function Naming Patterns'''
all assertions are removed by the compiler (the java equivalent of #defines)
 
by flipping the debug flag in the Assert class.
 
<H2>
 
<I><FONT SIZE=+1>3. SelfTest Methods</FONT></I></H2>
 
Each package will include a SelfTest class.&nbsp; This class should have
 
routines to thoroughly unit test every class in the package.&nbsp; If appropriate,
 
the SelfTest class may also contain methods for integration test between
 
the classes in this package, and between the classes in this package and
 
their dependancies in other packages.
 
  
<P>Here is the rule.&nbsp; When you design your class, you should design
+
* Get and set methods should begin with "get" / "set" and return the appropriate object type.
its unit test.&nbsp; When you design your package, you should design your
+
* Boolean get methods should use "is" or "can" as a prefix, such as "isUndoable()" rather than "getUndoable()".
integration test.&nbsp; You are NOT done with the implementation of a class
 
until its unit test is implemented and can be run successfully.&nbsp; You
 
are NOT done with your package implementation until all unit test are coded
 
and run successfully, and the integration tests (if appropriate) are coded
 
and run successfully.</UL>
 
  
<FONT SIZE=+1><B>Parentheses</B>&nbsp;</FONT>
+
'''Constants'''
  
<P>1) are recommend for Boolean expressions to ensure proper evaluation
+
* Constants will use all uppercase and will have words separated by underscores.
  
<P><I>example:</I>
+
'''General Varibles and Paramters Names'''
<BR>&nbsp;
 
<DD>
 
<TT><FONT FACE="Courier New,Courier">&nbsp;&nbsp;&nbsp; </FONT></TT><FONT SIZE=-1>if
 
(((someValue&lt;foo(theParm)) &amp;&amp; anotherValue) || todayIsMyBirthday)</FONT></DD>
 
  
<BR><FONT SIZE=-1>&nbsp;</FONT>
+
* Variables and parameters will begin with a lower case, and have mixed case. For example, fooBarReader.
<BR>TIP: Place constants on the left side of your expressions; assignment,
+
* Member variables should begin with "m". For example, mMemberVariable.
boolean and otherwise. This technique can catch assignment (versus equality)
 
errors, as well as promote constant factoring for poor quality compilers.&nbsp;
 
  
This is the preferred way to write expressions, though (especially in Java
+
=== Constants ===
where mistakes are generally caught by the compiler) the "traditional"
 
method where constants are on the right side is acceptable.&nbsp; Remember,
 
though, your code may be ported to C++ someday...
 
  
<P><B><FONT SIZE=+1>Constants</FONT></B>
+
Constants should be used when the same values needs to used in several places, and the actual values is either arbitrary or subject to possible
<BR>Constants should be used when the same values needs to used in several
+
change. For example, if in a number of places you are using buffers, and you expect to try tuning the buffer size for best performance, then
places, and the actual values is either arbitrary or subject to possible
+
use a constant because you expect to change the value. Another example is exception ids where the value itself does not matter, and the constant identifier is far more mnemonic and readable. Constants should not be used for values that you know will be referenced only once (e.g. ID_FOR_EXCEPTION_THIS_METHOD_THROWS) or for values that are not (reasonably) expected to change (e.g. NUMBER_OF_SUPREME_COURT_JUSTICES,
change.&nbsp; For example, if in a number of places you are using buffers,
+
or NUMBER_OF_DAYS_IN_WEEK). If you think the calculation needs clarification, include this information in comments, but adding constant identifies in some cases simply slows the compiler and makes the code harder to read. This is a really tough judgement call, so think carefully.
and you expect to try tuning the buffer size for best performance, then
 
use a constant because you expect to change the value.&nbsp; Another example
 
is exception ids where the value itself does not matter, and the constant
 
identifier is far more mnemonic and readable.&nbsp; Constants should not
 
be used for values that you know will be referenced only once (e.g. ID_FOR_EXCEPTION_THIS_METHOD_THROWS)or
 
for values that are not (reasonably) expected to change (e.g. NUMBER_OF_SUPREME_COURT_JUSTICES,
 
or NUMBER_OF_DAYS_IN_WEEK).&nbsp; If you think the calculation needs clarification,
 
include this information in comments, but adding constant identifies in
 
some cases simply slows the compiler and makes the code harder to read.&nbsp;
 
This is a really tough judgement call, so think carefully.
 
<BR><FONT FACE="Courier New"><FONT SIZE=+2>&nbsp;</FONT></FONT>
 
  
<TABLE BORDER=0 COLS=1 WIDTH="100%" BGCOLOR="#CCFFFF" >
+
=== Java Grammar ===
<TR>
 
<TD><A NAME="Source Code Style"></A><FONT SIZE=+3>Source Code Style Guidelines&nbsp;</FONT></TD>
 
</TR>
 
</TABLE>
 
&nbsp;
 
<H3>
 
Copyright Notice</H3>
 
This text, as a minimum, should be places at the top of all source files
 
which are not made publicly available:
 
<BR>&nbsp;
 
<DD>
 
<TT>/* ======================================================</TT></DD>
 
  
<DD>
+
* Wherever appropriate, avoid code that embeds many operations in a single line.  For example, avoid:
  
<TT>&nbsp;* Copyright (c) 1997 Netscape Communications Corporation</TT></DD>
+
    someObject.doThis( i++, otherObject.someField.doThat(), x?y:z );
  
<DD>
+
This kind of code is error prone, difficult to decipher, and hard to maintain.
<TT>&nbsp;* This file contains proprietary information of Netscape Communications.</TT></DD>
 
  
<DD>
+
== Classes ==
<TT>&nbsp;* Copying or reproduction without prior written approval is prohibited.</TT></DD>
 
  
<BR><TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * ======================================================
+
* classes should have the following form:
*/</TT>
 
  
<P><B><I><FONT SIZE=+1>Method Orderings</FONT></I></B>
+
    public class MyClass
 +
    {
 +
        ...
 +
    }
  
<P><I>The methods in a class should be grouped, and ordered in the following
+
'''NOT''' like this:
format:</I>
 
<UL>
 
<LI>
 
<I>Constructor</I></LI>
 
  
<LI>
+
    public class MyClass {
<I>finalizer (Destructor)</I></LI>
+
        ...
 +
    }
  
<LI>
+
== Methods ==
<I>public methods</I></LI>
 
  
<LI>
+
'''Method Orderings'''
  
<I>private methods</I></LI>
+
The methods in a class should be grouped, and ordered in the following format:
  
<LI>
+
* Constructor
<I>debugging methods</I></LI>
+
* finalizer (Destructor)
</UL>
+
* public methods
<I>Each group of methods can be optionally attached with comment block
+
* protected methods
in addition to individual method comment. For example,</I>
+
* private methods
<UL><I>/* ======================================================= *</I>
+
* debugging methods
<BR><I>&nbsp;&nbsp;&nbsp;&nbsp; CONSTRUCTOR METHODS (OPTIONAL)</I>
 
<BR><I>&nbsp;* =======================================================
 
*/</I>
 
<BR><I>/**</I>
 
  
<BR><I>&nbsp;* Constructs a certificate server</I>
 
<BR><I>&nbsp;*/</I>
 
<BR><I>&nbsp;public CertificateServer() {</I>
 
<BR><I>&nbsp;&nbsp; ...</I>
 
<BR><I>&nbsp;}</I></UL>
 
<B><FONT SIZE=+1>Line Spacing</FONT></B>
 
  
<P>Line width should not ordinarily exceed 80 characters. Use your best
+
Each group of methods can be optionally attached with a comment block in addition to individual method comments. For example:
judgment.
 
<BR>Tab sizes are to be set equal to 4 spaces. Tabs should be expanded
 
to spaces.
 
  
<P><B><FONT SIZE=+1>Braces</FONT></B>
+
    /* =======================================================
 +
    * CONSTRUCTOR METHODS (OPTIONAL)
 +
    * =======================================================
 +
    */
 +
   
 +
    /*
 +
    * Constructs a certificate server
 +
    */
 +
   
 +
    public CertificateServer()
 +
    {
 +
        ...
 +
    }
  
<P>The starting brace can be optionally at the end of the condictional
+
== Statements ==
or on the next line aligned with the conditional. The ending
 
<BR>brace must be on a separate line and aligned with the conditional.
 
It is strongly recommened that all conditional constructs
 
<BR>define a block of code for single lines of code.
 
  
<P>We give some options below to accommodate the vast majority of programmer's
+
* '''If / Else'''
styles.&nbsp; HOWEVER, be consistent!&nbsp; When
 
<BR>you pick a style, stick to it.&nbsp; When editing another person's
 
code, use your own judgement.&nbsp; As a default position, mimic the
 
<BR>style of the coder if you are just changing a small amount of code
 
within some existing function.&nbsp; Use whatever style you feel
 
  
<BR>appropriate when writing new methods.
+
Place the IF keyword and conditional expression on the same line. Always use the braces around the statement block, even if it is only one line.  Put the starting brace after the expression on the same line. If you have an else, put the closing brace, the else, and the opening brace on the same line.
  
<P><B><FONT SIZE=+1>Parentheses</FONT></B>
+
    if (expression) {
 +
        statement;
 +
    } else {
 +
        statement;
 +
    }
  
<P>1) are recommend for Boolean expressions to ensure proper evaluation
+
* '''WHILE'''
  
<P>example:
+
The WHILE construct uses the same layout format as the IF construct.  The WHILE keyword should appear on its own line, immediately followed by the conditional expression, and finally by the opening brace. Always use braces, even if the body is only a single line. Indent the body 4 spaces.
<BR>&nbsp;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (((someValue&lt;foo(theParm))
 
&amp;&amp; anotherValue) || todayIsMyBirthday)
 
<BR>&nbsp;
 
<BR>TIP: Place constants on the left side of your expressions; assignment,
 
boolean and otherwise. This technique can catch
 
<BR>assignment (versus equality) errors, as well as promote constant factoring
 
for poor quality compilers.&nbsp; This is the preferred
 
  
<BR>way to write expressions, though (especially in Java where mistakes
+
    while (expression) {
are generally caught by the compiler) the "traditional"
+
        statement;
<BR>method where constants are on the right side is acceptable.
+
    }
  
<P><B><FONT SIZE=+1>If / Else</FONT></B>
+
    do (expression) {
 +
        statement;
 +
    } while (expression);
  
<P>Place the IF keyword and conditional expression on the same line. Always
+
* '''SWITCH'''
use the braces around the statement block, even if
 
<BR>it is only one line.&nbsp; Put the starting brace after the expression
 
on the same line.&nbsp; If you have an else, but the closing brace, the
 
<BR>else, and the opening brace on the same line.
 
  
<P>&nbsp;&nbsp;&nbsp;&nbsp; example:
+
The SWITCH construct uses the same layout format as the IF construct.  The SWITCH keyword should appear on its own line, immediately followed by its test expression and then the opening brace. The case expressions may be indented, but need not be.  The lines between the case expression should be indented 4 spaces.  If possible, SWITCH constructs should always contain a "default" condition.
<BR>&nbsp;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
if (expression) {
 
  
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
    switch (expression) {
statement;
+
    case n:
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
        statement;
} else {
+
        break;
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
    default:&nbsp; //always add the default case
statement;
+
        statement;
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
        break;
}
+
    }
  
<P><B><FONT SIZE=+1>WHILE</FONT></B>
+
* '''Try/Catch/Finally'''
  
<P>The WHILE construct uses the same layout format as the IF construct.
+
The try/catch construct is similar to the others. The TRY keyword should appear on its own line; followed by the open brace on the same line; followed by the statement body; the close brace should be on the same line with the CATCH keyword.  Any number of CATCH phrases are next consisting of the closing brace, the CATCH keyword and the exception expression, the opening brace; followed by the CATCH body; followed by the close brace.  The FINALLY clause is the same as a CATCH.
The WHILE keyword should appear on its own line,
 
<BR>immediately followed by the conditional expression, and finally by
 
the opening brace. Always use braces, even if the body is
 
<BR>only a single line.&nbsp; Indent the body 4 spaces.
 
  
<P>&nbsp;&nbsp;&nbsp;&nbsp; example:
+
    try {
 +
        statement;
 +
    } catch (expression1) {
 +
        statement;
 +
    } catch (expression2) {
 +
        statement;
 +
    } finally {
 +
        statement;
 +
    }
  
<BR>&nbsp;
+
== Comments and Documentation ==
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
while (expression) {
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
}
 
  
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
'''Commenting Code'''
do (expression) {
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
} while (expression);
 
<BR>&nbsp;
 
  
<P><B><FONT SIZE=+1>SWITCH</FONT></B>
+
* Either C-style comments (/* */), or C++-style comments (//) may be used within Java programs.  If a change is being made to an existing class which uses one particular style exclusively, please continue to use this comment style for consistency.
 +
* All interfaces and public classes should have JavaDoc comments. Here are some guidelines:
 +
** Describe the class and what it is expected to do.  This is the most important doc.
 +
** Link in any notable subclasses.
 +
** Write javadoc descriptions of the methods.  Include a short description of each parameter.
 +
** Document the instance and static variables.</LI>
 +
** DO NOT write "content free help", (e.g. - a comment that simply reiterates the name of the function, or the return type, is worse than no comment at all).  Leave the comment empty if you can not add anything more than the method name and/or return type.
 +
** See the [http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javadoc.html "Javadoc API"] page for more information.
  
<P>The SWITCH construct uses the same layout format as the if construct.
+
'''Method Documentation'''
The SWITCH keyword should appear on its own
 
<BR>line, immediately followed by its test expression and then the opening
 
brace. The case expressions may be indented, but need
 
<BR>not be.&nbsp; The lines between the case expression should be indented
 
4 spaces.
 
<BR>&nbsp;
 
<BR>&nbsp;&nbsp;&nbsp; example:
 
  
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
The following standard has been established for the documentation of methods and functions.  Optional items are to be included only where applicable.  A complete description of each section in the routine documentation follows.
switch (expression) {
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
case n:
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
break;
 
  
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
The header is designed to be easy to use.  Many items are optional, and may be omitted where they are not applicable.  Each line item begins with an asterisk, and ends with blank space.  You do not place an asterisk next to each line in a multi-line component, only the topmost, next to the title.  All subsequent lines in multi-line component are to be indented so that they line up vertically with the previous line.
default:&nbsp; //always add the default case
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
break;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
}
 
  
<P><B><FONT SIZE=+1>Try/Catch/Finally</FONT></B>
+
    /**
 +
    * &lt;Detailed description of method.&gt;
 +
    *
 +
    * @param      &lt;Description of each parameter&gt;
 +
    * @return    &lt;explain each return type&gt;
 +
    * @exception  &lt;explain each exception&gt;
 +
    * @author    &lt;your name&gt;  &lt;06-13-07  3:57pm&gt;
 +
    **/
  
<P>The try/catch construct is similar to the others.&nbsp; TRY keyword
+
Here are a list of points that you may want to cover when writing the description of the method:
should appear on its own line; followed by the open brace on
 
<BR>the same line; followed by the statement body; the close brace should
 
be on the same line with the CATCH.&nbsp; Any number of
 
  
<BR>CATCH phrases are next consisting of the closing brace, the CATCH keyword
+
* intent of method
and the exception expression, the opening
+
* pre and post conditions
<BR>brace; followed by the CATCH body; followed by the close brace.&nbsp;
+
* side effects
The FINALLY clause is the same as a CATCH.
+
* dependencies
 +
* implementation notes
 +
* who should be calling this method
 +
* whether the method should or should not be overridden
 +
* where to invoke super when overriding control flow or state dependencies that need to exist before calling this method.
  
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
== Indentation, Braces, and Parentheses ==
try {
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
} catch (expression1) {
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
} catch (expression2) {
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
  
} finally {
+
'''Line Spacing'''
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
}
 
<BR>&nbsp;
 
<BR>&nbsp;
 
<TABLE BORDER=0 COLS=1 WIDTH="100%" BGCOLOR="#CCFFFF" >
 
<TR>
 
<TD><A NAME="Documentation for Methods and Functions"></A><FONT SIZE=+3>JavaDoc
 
Comments</FONT></TD>
 
</TR>
 
</TABLE>
 
All interfaces and public classes should have JavaDoc comments.&nbsp; Here
 
are some guidelines:
 
<UL>
 
  
<LI>
+
* Try to keep lines 80 characters or less.
spend some time describing the class and what it is expected to do.&nbsp;
+
* Indentation is 4 spaces.
This is the most important doc.</LI>
+
* No tabs, use spaces. Your editor should take care of most of this but in patches tabs stick out like sore thumbs.  
  
<UL>
+
'''Braces'''
<LI>
 
If you know of notable subclasses, try to link them in since navigating
 
down is difficult without it</LI>
 
</UL>
 
  
<LI>
+
For classes, the starting brace should be placed on the next line aligned with the class. The ending brace must be on a separate line and aligned with starting brace of the class.
next, time permitting, write javadoc descriptions of the methods.&nbsp;
 
Include a short description of each parameter.</LI>
 
  
<LI>
+
For methods within classes, the starting brace should be placed on the next line aligned with the method.  The ending brace must be on a separate line and aligned with starting brace of the method.
finally, once all above is done, document the instance and static variables.</LI>
 
  
<LI>
+
For conditionals, loops, and similar constructs, the starting brace should be placed at the end of the conditional, loop, etc. The ending brace must be on a separate line and aligned with the conditional, loop, etc.
DO NOT write "content free help", e.g. a comment that simply reiterates
 
the name of the function, or the return type, is worse than no comment
 
at all.&nbsp; Leave the comment empty if you can not add anything more
 
than the method name and/or return type.</LI>
 
</UL>
 
You may want to check some <A HREF="http://warp/client/xena/devcentral/docs/Javadoc_Basics.html">JavaDoc
 
Basics</A> available on warp, or the official <A HREF="http://www.javasoft.com/products/jdk/1.1/docs/tooldocs/win32/javadoc.html">JavaDoc
 
documentation</A>.
 
  
<H3>
+
Braces should always be used, even when they encapsulate a single line of code.
Method Documentation</H3>
 
The following standard has been established for the documentation of methods
 
and functions. Optional items are to be included only where applicable.
 
A complete description of each section in the routine documentation follows.
 
  
<P>The header is designed to be easy to use. Many items are optional, and
+
We give some options below to accommodate the vast majority of programmer's styles. HOWEVER, be consistent!  When you pick a style, stick to it. When editing another person's code, use your own judgement. As a default position, mimic the style of the coder if you are just changing a small amount of code within some existing function. Use whatever style you feel appropriate when writing new methods.
may be omitted where they are not applicable. Each line item begins with
 
an asterisk, and ends with blank space. You do not place an asterisk next
 
to each line in a multiline component, only the topmost, next to the title.
 
All subsequent lines in multiline component are to be indented so that
 
they line up vertically with the previous line.
 
  
<P><I>&nbsp;&nbsp;&nbsp; example:</I>
+
'''Parentheses'''
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
/**</TT></DD>
 
  
<DD>
+
Parentheses are recommend for Boolean expressions to ensure proper evaluation:
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* &lt;Detailed description of method.></TT></DD>
 
  
<DD>
+
    if((( someValue &lt; foo( theParm )) &amp;&amp; anotherValue ) || todayIsMyBirthday );
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
*</TT></DD>
 
  
<DD>
+
TIP: Place constants on the left side of your expressions; assignment, boolean, and otherwise. This technique can catch assignment (versus equality) errors, as well as promote constant factoring for poor quality compilers.
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* @param&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;Description of each parameter></TT></DD>
 
  
<DD>
+
This is the preferred way to write expressions, though (especially in Java where mistakes are generally caught by the compiler) the "traditional" method where constants are on the right side is acceptable.
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* @return&nbsp;&nbsp;&nbsp;&nbsp; &lt;explain each return type></TT></DD>
 
  
<DD>
+
== Debugging ==
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* @exception&nbsp; &lt;explain each exception></TT></DD>
 
  
<DD>
+
# Read about the precedence order of operators in Java.  For example, see this  [http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html "Operators"] document.
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
# Read about abnormal exception handling in Java.  For example, see this [http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html "Exceptions"] document.
* @author&nbsp;&nbsp;&nbsp;&nbsp; &lt;your name>&nbsp;&nbsp; &lt;04-22-97
+
# Make sure ''every'' path of execution through your code has been thoroughly tested.  Try actually stepping through each line!  While you're hard at work testing your code, be sure to throw invalid inputs at every public interface you provide. The last thing we want to do is crash because ''your'' routine didn't handle invalid inputs from ''ours''.
3:57pm></TT></DD>
+
# Calculate comparison values once; reuse them often.
 +
# Avoid global variables since they can wreak havoc with the pre-fetch instruction queue.
  
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
**/</TT></DD>
 
  
 +
It is our policy to produce code that can test itself to the greatest extent possible.  To that end, we encourage the use of three debugging techniques:
  
<P>Here are a list of points that you may want to cover when writing the
+
* asserts,
description of the method:
+
* pre/post conditions, and
<UL>
+
* self testing methods.
<LI>
 
intent of method</LI>
 
  
<LI>
+
''1. Asserts''
pre and post conditions</LI>
 
  
<LI>
+
It is highly recommended that assert methods (warnings/errors) be used to aid in debugging, especially to verify assumptions made in code. This
 +
will be the technique used for reporting run-time errors and warnings. See [http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html "Programming with Assertions"] for details.
  
side effects</LI>
+
''2. Pre and Post Conditions''
  
<LI>
+
In order to bulletproof your code, you should use asserts to test all boundary conditions. You aren't doing anyone any favors by "defensive" programming practices that allow clients of your code to make improper calls.  In other words, it is better to blow up (in debug builds) if you are given bad data than to try to "fix" the data and therefore hide bugs.
dependencies</LI>
 
  
<LI>
+
    String copyString(String aNewString)
implementation notes</LI>
+
    {
 +
        Assert.PreCondition( NULL != aNewString, "Null string given" );
 +
        ...
 +
        Assert.PostCondition( fSelfString.length() >= aNewString.length(), "lengths don't match after copy." );
 +
    }
  
<LI>
+
We do not want debug code to be included in release builds. Therefore, all assertions are removed by the compiler (the java equivalent of #defines) by flipping the debug flag in the Assert class.
who should be calling this method</LI>
 
  
<LI>
+
''3. SelfTest Methods''
whether the method should or should not be overridden</LI>
 
  
<LI>
+
Each package will include a SelfTest class.  This class should have routines to thoroughly unit test every class in the package.  If appropriate, the SelfTest class may also contain methods for integration testing between the classes in this package, and between the classes in this package and their dependancies in other packages.
where to invoke super when overriding</LI>
 
  
<BR>control flow or state dependencies that need to exist before calling
+
Here is the rule.  When you design your class, you should design its unit test.  When you design your package, you should design your
this method.</UL>
+
integration test.  You are NOT done with the implementation of a class until its unit test is implemented and can be run successfully.  You
 +
are NOT done with your package implementation until all unit test are coded and run successfully, and the integration tests (if appropriate) are coded and run successfully.

Latest revision as of 02:22, 25 February 2008

Why Have A Coding Style?

For easier maintenance

If you're merging changes from a patch it's much easier if everyone is using the same coding style. This isn't the reality for a lot of our code, but we're trying to get to the point where most of it uses the same style.

Improved readability

Remember, code isn't just for compilers, it's for people, too. If it wasn't for people, we would all be programming in assembly. Coding style and consistency mean that if you go from one part of the code to another you don't spend time having to re-adjust from one style to another. Blocks are consistent and readable and the flow of the code is apparent. Coding style adds value for people who have to read your code after you've been hit by a bus. Remember that.

General Rules

  • All source files should include a copy of the license.
  • Space after keywords
  • Curly braces on new line following a class.
  • Curly braces on new line following a method.
  • Curly braces on same line as if/while/switch.
  • All code should be peer reviewed before being checked in.

Naming Conventions

Package Names

  • Package names should be single lowercase words.
  • Dogtag Certificate System-specific packages should be sub-packages of "com.netscape.certsrv".

Interface Names

  • Interface names should begin with "I". For example, IConfigStore.

Exception Names

  • Exceptions should have their own hierarchy in each certificate server subsystem. (This implies that each subsystem should define a new exception that extends the base exception ECSException).

Class Names

  • Concrete classes should use natural descriptive names, begin with a capital, and have mixed case. For example, FooBarReader.

Member Function Names

  • Method ("member function") names should begin with a lowercase letter with each subsequent new word in uppercase, and subsequent letters in each word in lower case.
  • Methods for debug-only implementations should begin with "debug".
  • Static methods should begin with a capital letter with each subsequent new word in uppercase, and subsequent letters in each word in lower case.
   public class MyClass
   {
       void doSomethingNeat(int aValue);
       void debugDumpToScreen();
       static void SomeClassMethod(int aValue);
   }

Component Factory Names

A component factory is a public class that implements only static methods. These static methods are "Factory functions" or "component constructors". Factory class names should include the word "Factory". Factory method names should start with the word "Make." For example:

   public class WidgetFactory
   {
       static Button MakeButton(int aButtonType);
       static ListBox MakeListBox();
   }

Function Naming Patterns

  • Get and set methods should begin with "get" / "set" and return the appropriate object type.
  • Boolean get methods should use "is" or "can" as a prefix, such as "isUndoable()" rather than "getUndoable()".

Constants

  • Constants will use all uppercase and will have words separated by underscores.

General Varibles and Paramters Names

  • Variables and parameters will begin with a lower case, and have mixed case. For example, fooBarReader.
  • Member variables should begin with "m". For example, mMemberVariable.

Constants

Constants should be used when the same values needs to used in several places, and the actual values is either arbitrary or subject to possible change. For example, if in a number of places you are using buffers, and you expect to try tuning the buffer size for best performance, then use a constant because you expect to change the value. Another example is exception ids where the value itself does not matter, and the constant identifier is far more mnemonic and readable. Constants should not be used for values that you know will be referenced only once (e.g. ID_FOR_EXCEPTION_THIS_METHOD_THROWS) or for values that are not (reasonably) expected to change (e.g. NUMBER_OF_SUPREME_COURT_JUSTICES, or NUMBER_OF_DAYS_IN_WEEK). If you think the calculation needs clarification, include this information in comments, but adding constant identifies in some cases simply slows the compiler and makes the code harder to read. This is a really tough judgement call, so think carefully.

Java Grammar

  • Wherever appropriate, avoid code that embeds many operations in a single line. For example, avoid:
   someObject.doThis( i++, otherObject.someField.doThat(), x?y:z );

This kind of code is error prone, difficult to decipher, and hard to maintain.

Classes

  • classes should have the following form:
   public class MyClass
   {
       ...
   }

NOT like this:

   public class MyClass {
       ...
   }

Methods

Method Orderings

The methods in a class should be grouped, and ordered in the following format:

  • Constructor
  • finalizer (Destructor)
  • public methods
  • protected methods
  • private methods
  • debugging methods


Each group of methods can be optionally attached with a comment block in addition to individual method comments. For example:

   /* =======================================================
    * CONSTRUCTOR METHODS (OPTIONAL)
    * =======================================================
    */
   
   /*
    * Constructs a certificate server
    */
   
   public CertificateServer()
   {
       ...
   }

Statements

  • If / Else

Place the IF keyword and conditional expression on the same line. Always use the braces around the statement block, even if it is only one line. Put the starting brace after the expression on the same line. If you have an else, put the closing brace, the else, and the opening brace on the same line.

   if (expression) {
       statement;
   } else {
       statement;
   }
  • WHILE

The WHILE construct uses the same layout format as the IF construct. The WHILE keyword should appear on its own line, immediately followed by the conditional expression, and finally by the opening brace. Always use braces, even if the body is only a single line. Indent the body 4 spaces.

   while (expression) {
       statement;
   }
   do (expression) {
       statement;
   } while (expression);
  • SWITCH

The SWITCH construct uses the same layout format as the IF construct. The SWITCH keyword should appear on its own line, immediately followed by its test expression and then the opening brace. The case expressions may be indented, but need not be. The lines between the case expression should be indented 4 spaces. If possible, SWITCH constructs should always contain a "default" condition.

   switch (expression) {
   case n:
       statement;
       break;
   default:  //always add the default case
       statement;
       break;
   }
  • Try/Catch/Finally

The try/catch construct is similar to the others. The TRY keyword should appear on its own line; followed by the open brace on the same line; followed by the statement body; the close brace should be on the same line with the CATCH keyword. Any number of CATCH phrases are next consisting of the closing brace, the CATCH keyword and the exception expression, the opening brace; followed by the CATCH body; followed by the close brace. The FINALLY clause is the same as a CATCH.

   try {
       statement;
   } catch (expression1) {
       statement;
   } catch (expression2) {
       statement;
   } finally {
       statement;
   }

Comments and Documentation

Commenting Code

  • Either C-style comments (/* */), or C++-style comments (//) may be used within Java programs. If a change is being made to an existing class which uses one particular style exclusively, please continue to use this comment style for consistency.
  • All interfaces and public classes should have JavaDoc comments. Here are some guidelines:
    • Describe the class and what it is expected to do. This is the most important doc.
    • Link in any notable subclasses.
    • Write javadoc descriptions of the methods. Include a short description of each parameter.
    • Document the instance and static variables.</LI>
    • DO NOT write "content free help", (e.g. - a comment that simply reiterates the name of the function, or the return type, is worse than no comment at all). Leave the comment empty if you can not add anything more than the method name and/or return type.
    • See the "Javadoc API" page for more information.

Method Documentation

The following standard has been established for the documentation of methods and functions. Optional items are to be included only where applicable. A complete description of each section in the routine documentation follows.

The header is designed to be easy to use. Many items are optional, and may be omitted where they are not applicable. Each line item begins with an asterisk, and ends with blank space. You do not place an asterisk next to each line in a multi-line component, only the topmost, next to the title. All subsequent lines in multi-line component are to be indented so that they line up vertically with the previous line.

   /**
    * <Detailed description of method.>
    *
    * @param      <Description of each parameter>
    * @return     <explain each return type>
    * @exception  <explain each exception>
    * @author     <your name>   <06-13-07  3:57pm>
    **/

Here are a list of points that you may want to cover when writing the description of the method:

  • intent of method
  • pre and post conditions
  • side effects
  • dependencies
  • implementation notes
  • who should be calling this method
  • whether the method should or should not be overridden
  • where to invoke super when overriding control flow or state dependencies that need to exist before calling this method.

Indentation, Braces, and Parentheses

Line Spacing

  • Try to keep lines 80 characters or less.
  • Indentation is 4 spaces.
  • No tabs, use spaces. Your editor should take care of most of this but in patches tabs stick out like sore thumbs.

Braces

For classes, the starting brace should be placed on the next line aligned with the class. The ending brace must be on a separate line and aligned with starting brace of the class.

For methods within classes, the starting brace should be placed on the next line aligned with the method. The ending brace must be on a separate line and aligned with starting brace of the method.

For conditionals, loops, and similar constructs, the starting brace should be placed at the end of the conditional, loop, etc. The ending brace must be on a separate line and aligned with the conditional, loop, etc.

Braces should always be used, even when they encapsulate a single line of code.

We give some options below to accommodate the vast majority of programmer's styles. HOWEVER, be consistent! When you pick a style, stick to it. When editing another person's code, use your own judgement. As a default position, mimic the style of the coder if you are just changing a small amount of code within some existing function. Use whatever style you feel appropriate when writing new methods.

Parentheses

Parentheses are recommend for Boolean expressions to ensure proper evaluation:

   if((( someValue < foo( theParm )) && anotherValue ) || todayIsMyBirthday );

TIP: Place constants on the left side of your expressions; assignment, boolean, and otherwise. This technique can catch assignment (versus equality) errors, as well as promote constant factoring for poor quality compilers.

This is the preferred way to write expressions, though (especially in Java where mistakes are generally caught by the compiler) the "traditional" method where constants are on the right side is acceptable.

Debugging

  1. Read about the precedence order of operators in Java. For example, see this "Operators" document.
  2. Read about abnormal exception handling in Java. For example, see this "Exceptions" document.
  3. Make sure every path of execution through your code has been thoroughly tested. Try actually stepping through each line! While you're hard at work testing your code, be sure to throw invalid inputs at every public interface you provide. The last thing we want to do is crash because your routine didn't handle invalid inputs from ours.
  4. Calculate comparison values once; reuse them often.
  5. Avoid global variables since they can wreak havoc with the pre-fetch instruction queue.


It is our policy to produce code that can test itself to the greatest extent possible. To that end, we encourage the use of three debugging techniques:

  • asserts,
  • pre/post conditions, and
  • self testing methods.

1. Asserts

It is highly recommended that assert methods (warnings/errors) be used to aid in debugging, especially to verify assumptions made in code. This will be the technique used for reporting run-time errors and warnings. See "Programming with Assertions" for details.

2. Pre and Post Conditions

In order to bulletproof your code, you should use asserts to test all boundary conditions. You aren't doing anyone any favors by "defensive" programming practices that allow clients of your code to make improper calls. In other words, it is better to blow up (in debug builds) if you are given bad data than to try to "fix" the data and therefore hide bugs.

   String copyString(String aNewString)
   {
       Assert.PreCondition( NULL != aNewString, "Null string given" );
       ...
       Assert.PostCondition( fSelfString.length() >= aNewString.length(), "lengths don't match after copy." );
   }

We do not want debug code to be included in release builds. Therefore, all assertions are removed by the compiler (the java equivalent of #defines) by flipping the debug flag in the Assert class.

3. SelfTest Methods

Each package will include a SelfTest class. This class should have routines to thoroughly unit test every class in the package. If appropriate, the SelfTest class may also contain methods for integration testing between the classes in this package, and between the classes in this package and their dependancies in other packages.

Here is the rule. When you design your class, you should design its unit test. When you design your package, you should design your integration test. You are NOT done with the implementation of a class until its unit test is implemented and can be run successfully. You are NOT done with your package implementation until all unit test are coded and run successfully, and the integration tests (if appropriate) are coded and run successfully.