Difference between revisions of "PKI Java Coding Style"

From Dogtag
Jump to: navigation, search
(General Coding Gudelines)
 
(59 intermediate revisions by 2 users not shown)
Line 1: Line 1:
== Introduction ==
+
== Why Have A Coding Style? ==
  
This manual contains the Java coding standards and guidelines for Fedora Certificate System contributors.  Fedora Certificate System-specific comments are in ''italics''.
+
=== For easier maintenance ===
  
== 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.
 +
 
 +
=== 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 ===
 
=== Naming Conventions ===
Line 10: Line 23:
  
 
* Package names should be single lowercase words.
 
* Package names should be single lowercase words.
* ''Fedora Certificate System-specific packages should be sub-packages of "com.netscape.certsrv"''.
+
* Dogtag Certificate System-specific packages should be sub-packages of "com.netscape.certsrv".
  
'''''Interface Names'''''
+
'''Interface Names'''
  
* ''Interface names should begin with "I". For example, IConfigStore''.
+
* Interface names should begin with "I". For example, IConfigStore.
  
'''''Exception Names'''''
+
'''Exception 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 ECSException).
* ''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'''
 
'''Class Names'''
  
* Concrete classes should use natural descriptive names, begin with a capital, and have mixed case:  ''FooBarReader''
+
* Concrete classes should use natural descriptive names, begin with a capital, and have mixed case. For example, FooBarReader.
* ''Abstract classes should begin with "A". For example, ABaseClass''.
 
  
 
'''Member Function Names'''
 
'''Member Function Names'''
Line 54: Line 65:
 
* Boolean get methods should use "is" or "can" as a prefix, such as "isUndoable()" rather than "getUndoable()".
 
* Boolean get methods should use "is" or "can" as a prefix, such as "isUndoable()" rather than "getUndoable()".
  
'''''Constants'''''
+
'''Constants'''
  
* ''Constants will use all uppercase and will have words separated by underscores''.
+
* Constants will use all uppercase and will have words separated by underscores.
  
'''''General Varibles and Paramters Names'''''
+
'''General Varibles and Paramters Names'''
  
* ''Variables and parameters will begin with a lower case, and have mixed case. For example, fooBarReader''.
+
* 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''.
+
* Member variables should begin with "m". For example, mMemberVariable.
 
 
'''Commenting Code'''
 
  
* All interfaces and public classes should have JavaDoc comments. See the [http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javadoc.html "Javadoc API"] page for more information.
+
=== Constants ===
  
== General Coding Gudelines ==
+
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'''
+
=== Java Grammar ===
  
 
* Wherever appropriate, avoid code that embeds many operations in a single line.  For example, avoid:
 
* Wherever appropriate, avoid code that embeds many operations in a single line.  For example, avoid:
  
     someObject.doThis(i++, otherObject.someField.doThat(), x?y:z)
+
     someObject.doThis( i++, otherObject.someField.doThat(), x?y:z );
  
 
This kind of code is error prone, difficult to decipher, and hard to maintain.
 
This kind of code is error prone, difficult to decipher, and hard to maintain.
  
'''Debugging'''
+
== Classes ==
  
# First and foremost, go read Writing Solid Code.  Now go back and reread the java programming language reference documentation to refresh your memory on the precedence order of operators.
+
* classes should have the following form:
# Now go read the <A HREF="ErrorHandling.html">Abnormal Condition Handling</A> document.
 
# You can never do enough coverage testing. Make sure ''every'' 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 ''your'' routine didn't handle invalid inputs from ''ours''.  Never '''''ever''''' break the build (except by prior agreement of all members of the team, for a specified purpose and duration.)
 
# 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>
+
    public class MyClass
<FONT SIZE=+1>Orthodox Cannonical Form</FONT></H1>
+
    {
 +
        ...
 +
    }
  
Don�t forget to adhere to our Orthodox Canonical Form. This is a template
+
'''NOT''' like this:
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
+
    public class MyClass {
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
+
== Methods ==
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
+
'''Method Orderings'''
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>
+
The methods in a class should be grouped, and ordered in the following format:
<FONT SIZE=-2>String copyString(String aOtherString)</FONT></DD>
 
  
<DD>
+
* Constructor
<FONT SIZE=-2>{</FONT></DD>
+
* finalizer (Destructor)
 +
* public methods
 +
* protected methods
 +
* private methods
 +
* debugging methods
  
<DD>
 
<FONT SIZE=-2>&nbsp;&nbsp;&nbsp; Assert.PreCondition(NULL != aOtherStr,
 
"Null string given");</FONT></DD>
 
  
<DD>
+
Each group of methods can be optionally attached with a comment block in addition to individual method comments. For example:
<FONT SIZE=-2>&nbsp;&nbsp;&nbsp; ...</FONT></DD>
 
  
<DD>
+
    /* =======================================================
<FONT SIZE=-2>&nbsp;&nbsp;&nbsp; Assert.PostCondition(fSelfString.length()
+
    * CONSTRUCTOR METHODS (OPTIONAL)
>=aOtherString.length(), "lengths don't match after copy.");</FONT></DD>
+
    * =======================================================
 +
    */
 +
   
 +
    /*
 +
    * Constructs a certificate server
 +
    */
 +
   
 +
    public CertificateServer()
 +
    {
 +
        ...
 +
    }
  
<DD>
+
== Statements ==
<FONT SIZE=-2>}</FONT></DD>
 
  
<DIR><FONT SIZE=-1>&nbsp;</FONT></DIR>
+
* '''If / Else'''
</DIR>
 
  
We do not want debug code to be included into release builds. Therefore,
+
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.
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
+
    if (expression) {
its unit test.&nbsp; When you design your package, you should design your
+
        statement;
integration test.&nbsp; You are NOT done with the implementation of a class
+
    } else {
until its unit test is implemented and can be run successfully.&nbsp; You
+
        statement;
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>
+
* '''WHILE'''
  
<P>1) are recommend for Boolean expressions to ensure proper evaluation
+
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.
  
<P><I>example:</I>
+
    while (expression) {
<BR>&nbsp;
+
        statement;
<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>
+
    do (expression) {
<BR>TIP: Place constants on the left side of your expressions; assignment,
+
        statement;
boolean and otherwise. This technique can catch assignment (versus equality)
+
    } while (expression);
errors, as well as promote constant factoring for poor quality compilers.&nbsp;
 
  
This is the preferred way to write expressions, though (especially in Java
+
* '''SWITCH'''
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>
+
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>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.&nbsp; 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.&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" >
+
    switch (expression) {
<TR>
+
    case n:
<TD><A NAME="Source Code Style"></A><FONT SIZE=+3>Source Code Style Guidelines&nbsp;</FONT></TD>
+
        statement;
</TR>
+
        break;
</TABLE>
+
    default:&nbsp; //always add the default case
&nbsp;
+
        statement;
<H3>
+
        break;
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>
+
* '''Try/Catch/Finally'''
  
<TT>&nbsp;* Copyright (c) 1997 Netscape Communications Corporation</TT></DD>
+
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.
  
<DD>
+
    try {
<TT>&nbsp;* This file contains proprietary information of Netscape Communications.</TT></DD>
+
        statement;
 +
    } catch (expression1) {
 +
        statement;
 +
    } catch (expression2) {
 +
        statement;
 +
    } finally {
 +
        statement;
 +
    }
  
<DD>
+
== Comments and Documentation ==
<TT>&nbsp;* Copying or reproduction without prior written approval is prohibited.</TT></DD>
 
  
<BR><TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; * ======================================================
+
'''Commenting Code'''
*/</TT>
 
  
<P><B><I><FONT SIZE=+1>Method Orderings</FONT></I></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><I>The methods in a class should be grouped, and ordered in the following
+
'''Method Documentation'''
format:</I>
 
<UL>
 
<LI>
 
<I>Constructor</I></LI>
 
  
<LI>
+
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.
<I>finalizer (Destructor)</I></LI>
 
  
<LI>
+
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.
<I>public methods</I></LI>
 
  
<LI>
+
    /**
 +
    * &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;
 +
    **/
  
<I>private methods</I></LI>
+
Here are a list of points that you may want to cover when writing the description of the method:
  
<LI>
+
* intent of method
<I>debugging methods</I></LI>
+
* pre and post conditions
</UL>
+
* side effects
<I>Each group of methods can be optionally attached with comment block
+
* dependencies
in addition to individual method comment. For example,</I>
+
* implementation notes
<UL><I>/* ======================================================= *</I>
+
* who should be calling this method
<BR><I>&nbsp;&nbsp;&nbsp;&nbsp; CONSTRUCTOR METHODS (OPTIONAL)</I>
+
* whether the method should or should not be overridden
<BR><I>&nbsp;* =======================================================
+
* where to invoke super when overriding control flow or state dependencies that need to exist before calling this method.
*/</I>
 
<BR><I>/**</I>
 
  
<BR><I>&nbsp;* Constructs a certificate server</I>
+
== Indentation, Braces, and Parentheses ==
<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
+
'''Line Spacing'''
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>
+
* 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.
  
<P>The starting brace can be optionally at the end of the condictional
+
'''Braces'''
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
+
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.
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.
+
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.
  
<P><B><FONT SIZE=+1>Parentheses</FONT></B>
+
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.
  
<P>1) are recommend for Boolean expressions to ensure proper evaluation
+
Braces should always be used, even when they encapsulate a single line of code.
  
<P>example:
+
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.
<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
+
'''Parentheses'''
are generally caught by the compiler) the "traditional"
 
<BR>method where constants are on the right side is acceptable.
 
  
<P><B><FONT SIZE=+1>If / Else</FONT></B>
+
Parentheses are recommend for Boolean expressions to ensure proper evaluation:
  
<P>Place the IF keyword and conditional expression on the same line. Always
+
    if((( someValue &lt; foo( theParm )) &amp;&amp; anotherValue ) || todayIsMyBirthday );
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:
+
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.
<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;
+
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.
statement;
 
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
} else {
 
<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><B><FONT SIZE=+1>WHILE</FONT></B>
+
== Debugging ==
  
<P>The WHILE construct uses the same layout format as the IF construct.
+
# 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.
The WHILE keyword should appear on its own line,
+
# 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.
<BR>immediately followed by the conditional expression, and finally by
+
# 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''.
the opening brace. Always use braces, even if the body is
+
# Calculate comparison values once; reuse them often.
<BR>only a single line.&nbsp; Indent the body 4 spaces.
+
# Avoid global variables since they can wreak havoc with the pre-fetch instruction queue.
  
<P>&nbsp;&nbsp;&nbsp;&nbsp; example:
 
  
<BR>&nbsp;
+
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:
<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;
+
* asserts,
do (expression) {
+
* pre/post conditions, and
<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
+
* self testing methods.
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>
+
''1. Asserts''
  
<P>The SWITCH construct uses the same layout format as the if construct.
+
It is highly recommended that assert methods (warnings/errors) be used to aid in debugging, especially to verify assumptions made in code. This
The SWITCH keyword should appear on its own
+
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.
<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;
+
''2. Pre and Post Conditions''
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;
+
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.
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>
+
    String copyString(String aNewString)
 
+
    {
<P>The try/catch construct is similar to the others.&nbsp; TRY keyword
+
        Assert.PreCondition( NULL != aNewString, "Null string given" );
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
+
        Assert.PostCondition( fSelfString.length() >= aNewString.length(), "lengths don't match after copy." );
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
 
and the exception expression, the opening
 
<BR>brace; followed by the CATCH body; followed by the close brace.&nbsp;
 
The FINALLY clause is the same as a CATCH.
 
 
 
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
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 {
 
<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>
 
spend some time describing the class and what it is expected to do.&nbsp;
 
This is the most important doc.</LI>
 
 
 
<UL>
 
<LI>
 
If you know of notable subclasses, try to link them in since navigating
 
down is difficult without it</LI>
 
</UL>
 
 
 
<LI>
 
next, time permitting, write javadoc descriptions of the methods.&nbsp;
 
Include a short description of each parameter.</LI>
 
 
 
<LI>
 
finally, once all above is done, document the instance and static variables.</LI>
 
 
 
<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.&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>
 
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
 
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>
 
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
/**</TT></DD>
 
 
 
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* &lt;Detailed description of method.></TT></DD>
 
 
 
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
*</TT></DD>
 
 
 
<DD>
 
<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>
 
<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>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* @exception&nbsp; &lt;explain each exception></TT></DD>
 
 
 
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
* @author&nbsp;&nbsp;&nbsp;&nbsp; &lt;your name>&nbsp;&nbsp; &lt;04-22-97
 
3:57pm></TT></DD>
 
 
 
<DD>
 
<TT>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
**/</TT></DD>
 
 
 
 
 
<P>Here are a list of points that you may want to cover when writing the
 
description of the method:
 
<UL>
 
<LI>
 
intent of method</LI>
 
 
 
<LI>
 
pre and post conditions</LI>
 
 
 
<LI>
 
 
 
side effects</LI>
 
 
 
<LI>
 
dependencies</LI>
 
 
 
<LI>
 
implementation notes</LI>
 
  
<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.