Many people helped with the evolution of this code standard. These practices were not created in a vacuum. They are tried and true rules that have been used in producing both research and commercial systems by teams of dozens of programmers. While not all the rules are applicable to every developer or all systems, a general adherence to the rules and a belief in software engineering practices often results in happier and healthier developers and systems.
com.otego package
hierarchy.
com.otego.otgbridge.
io
package similar to java.io. Other examples include
java.lang, java.net, java.util,
and java.math.
Provide a package.html file in each package directory
briefly outlining the purpose and structure of the package. This file
is used by Javadoc (in Java 1.2 and later) as package commentary, and
also serves as local documentation for your code tree. For more
information on the format of this file as used by Javadoc, see the
package-level comments documentation on Sun's web site. If you
plan to allow local browsing of your source tree, you should alias
this file to index.html so that it serves as the default
index file for the directory.
Place each and every class in a separate file. This applies even
to non-public classes (which are allowed by the Java compiler to be
placed in the same file as the main class using them), except in the
case of one-shot usages where the non-public class cannot conceivably
be used outside of its context. One example of such usage is the
creation of Event classes in AWT 1.1 programming.
Begin each file with a comment block containing at least the following information (example below):
Immediately follow the file header with:
package statement.
import list, ordered according to the following rules:
import
java.<packagename>" are listed last; imports of standard
Java extensions of the form "import
javax.<packagename>" are listed second last; and all remaining
imports come first.
import java.io.*"). Using this construct makes it
difficult to determine exactly which classes are referenced by your
class without detailed inspection of the code.
Example file header:
/*****************************************************************************
* Copyright (C) 2002 Otego AG, Switzerland. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the otego Software License *
* version 1.0, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package com.otego.project.sample;
import com.otego.project.otherpackage.FooObject;
import com.otego.project.otherpackage.MyObject;
import com.otego.otherproject.somepackage.MyObject;
import javax.management.timer.TimerMBean;
import javax.xml.parsers.SAXParser;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
Write all /** ... **/ comments using
Javadoc
conventions. Even though it is not required by Javadoc, end each
/** comment with **/ to make it easier to
read and check.
Preface each class with a /** ... **/ comment
describing the purpose of the class, guaranteed invariants, usage
instructions, and/or usage examples. The beginning of the comment
should be a description of the class in exactly one sentence. Also
include any reminders or disclaimers about required or desired
improvements. Use HTML format when appropriate, but do not forget that
all inline text is parsed as HTML format, so accidental use of HTML
elements can result in strange looking documentation. See the below
chart for appropriate tags and usages.
Each class comment block must include exactly one
@version tag and at least one @author tag.
The @author tags often list everyone who has written more
than a few lines of the class. Each @author tag should
list exactly one author including its email address. The
@version tag's version is a
project specific string (e.g. "${version}") which will be replaced by
Jakarta Ant (our preferred project building tool) followed by a CVS/RCS
$Id$ tag. Additionally, each class can optionally
contain a // comment after its closing brace stating
that the class declaration has ended.
Example class comment block:
<file header, package name and imports, as above>
/**
* A class representing the archetypical class from which one can
* learn code standards through example.
*
* Usage example:
* <CODE>
* ArchetypeClass ac = new ArchetypeClass();
* ac.init();
* </CODE>
*
* @see ArchetypeAbstractClass
* @see ArchetypeInterface
* @see java.lang.Object
* @version ${version} $Id: java_standard.html,v 1.9 2002/03/18 07:18:47 giacomo Exp $
* @author <a href="mailto:giacomo.pati@otego.com">Giacomo Pati</a>
* @author <a href="mailto:martin.biel@otego.com">Martin Biel</a>
**/
public class ArchetypeClass extends AnotherClass
implements FooInterface, BarInterface
{
...
}
// end of class ArchetypeClass
Use Javadoc conventions to describe the nature, purpose, constraints, and usage of static fields and instance fields. See the chart below for appropriate tags and usages. All static fields should appear together, before the set of method declarations; all instance fields should likewise appear together, after the set of static fields (but always before the method declarations). The sets of static and instance fields should be clearly offset by comments (the format of these comments is left to the individual programmer, though they should be clear).
For real OO-programming there is never a use of public instance variables. Those should be made available by use of getter and setter methods. Also, the convention for protected and public instance variables should be to prefix them with 'm_' to clearly show this fact. Why this? Simply because instance variables are potentially risky in the server-side programming concerning thread safetiness.For example:
public class Example
{
// Static Fields
/**
* This is a static field.
**/
priivate static String m_staticString = "Static String";
// Instance Fields
/**
* This is an instance field.
**/
protected String m_instanceString = "Instance String";
// Method Declarations
...
}
Method parameters should be cleanly organized, either on a single line or one per line. All static methods should appear together; the same goes for instance methods. These blocks of methods should be clearly delineated with comments (as for blocks of variables, above). Some examples of acceptable method declarations:
public static int aMethod( final String aString, final int anInt, final double aDouble );
public synchronized Exception anotherMethod( final String aString,
final int anInt,
final double aDouble );
public final Event yetAnotherMethod(
final Long aLongObject,
final String aString,
final Double aDoubleObject );
Whenever possible use the final modifier for variables,
methods and arguments. This enable the most performance optimization
and security constraints possible.
Use Javadoc conventions to describe nature, purpose, preconditions, effects, algorithmic notes, usage instructions, reminders, etc. The beginning of a method comment should be a summary of the method. Use HTML format when appropriate. See the chart below for appropriate tags and usages.
In all of the following tags, Expression means
(OCL-Expression | code segment | natural language
description). An OCL-Expression is an expression in
the Object Constraint Language; see Joe for more information. A
code segment is a legal expression from any programming
language, but is most often written in the language of the code it
documenting, in this case Java. A natural language
description is a description written in a spoken language (like
English).
For all tags, entities enclosed in () or
<> must be so enclosed when using the tags.
E.g. "(Expression)" means literally "(" + the expression + ")".
Entities enclosed in [] in the table indicate optional
entities and should not use literal square brackets.
The table lists, in the "Usage" column, the Java entities to which each tag is applicable. Possible values for this column are classes, interfaces, methods, fields (that is, instance fields and static fields of a class or interface), all (which means "classes, interfaces, methods and fields"), and special (special usages explained in the "Purpose/Description" column).
More detailed information on the syntax of the standard Javadoc
tags described here (most notably, @see,
{@link} and the serialization-related tags) is available
from Sun's Javadoc
Home Page.
| Tag | Usage | Purpose/Description |
| Meta-Information | ||
@author <a href="mailto:authors.mail@address.link>>Full Name</a> |
Classes, Interfaces | Lists an author of the class or interface. The
text has no special internal structure. A doc comment may contain
multiple @author tags. A standard author tag includes
only the full name of the author and should not include other
information (like an email address, web page, etc.) unless absolutely
necessary. |
@history Description |
All | Describes how a feature has been significantly modified over time. For each major change, the description should include: who made it, when it was made (date and version), what was done, why it was done, and a reference to the change request and/or user requirement that resulted in the change being made. |
| Pending Work | ||
@bug Description |
Classes, Interfaces, Methods | Describes a known bug in the class or method. One tag should be used for each bug. If a construct has a known bug, it should be described. Omission of a bug description is considered as bad an offense as the existence of the bug in the first place. |
@review Username - Description |
All | Suggests/Reminds a reader that a particular block of code still needs to be reviewed (by the named user) for some reason. Typical reasons include the "something's not right here" syndrome, boundary condition checks, not understanding an algorithm completely, etc. |
@todo Username - Description |
All | Describes some work that still needs to be accomplished by the named user. Typical examples include optimizing algorithms, proving correctness of new code, renaming fields or methods to conform to standards, cleaning up code, etc. |
@idea Username [Classifier] - Description |
All | Describes an idea for something from the named user. The optional <classifier> argument is for ad hoc categorization of ideas. Typical examples include optimizing algorithms, proving correctness of new code, renaming fields or methods to conform to standards, cleaning up code, etc. |
| Preconditions | ||
(@precondition | @pre) (Expression)
[<Throwable> -] [Description] |
Methods | Describes a precondition which must be true before the method can be safely invoked. One tag is used for each precondition. If a precondition is violated Throwable is thrown. |
@requires (Expression) Description |
All | Describes assumptions about execution context. In particular, describes any reliance on actions in other threads to terminate or provide notifications. Requires expressions are usually not expressible in code and cannot be tested at runtime. |
| Postconditions | ||
(@postcondition | @post) (Expression)
[<Throwable> -] Description |
Methods | Describes a postcondition which is true after a
method has completed, successfully or not. If a postcondition is
violated Throwable is thrown. Postconditions that throw
exceptions interact with the standard Java exception mechanism and
thus are described in the @exception
tag. One tag is used for each postcondition. |
@ensures (Expression) Description |
Classes, Methods | Specifies the semantics of an element's behavior and any guarantees it makes. Ensures expressions are usually not expressible in code and cannot be tested at runtime. |
@generates (Expression) [Description] |
Classes, Methods | Describes new entities (for example,
Threads) constructed as a result of the execution of
a method or the instantiation of a class. |
@modifies (SINGLE-ASSIGNMENT | QUERY | Expression) Description |
All | Indicates the semantics of a construct as follows:
|
| Invariants | ||
@invariant (Expression) [<Throwable>] Description |
Classes, Interfaces, Methods | Specifies a class, interface or method invariant.
An invariant is an expression which must evaluate to true whenever
the entity being described is in a stable state.
An invariant expression must evaluate to a boolean.
An object is defined as being in a stable state when either (a) no threads of control are within the object or operating upon the object, (b) a single thread of control is about to enter a method of the object, or (c) a single thread of control is about to exit a method of the object. If an invarient is violated when an object is in a stable state, a Throwable is thrown. |
| Concurrency Control | ||
@concurrency (SEQUENTIAL | GUARDED |
CONCURRENT | TIMEOUT <value> <Throwable> | FAILURE
<Throwable> | SPECIAL) [Description] |
All | Describes the concurrency strategy and/or approach
taken by (necessary for) the class/interface/method (field). The
execution context for a method should be described at this
point. The meanings of the possible parameters are as follows:
A method lacking a concurrency tag is considered CONCURRENT. The semantics description is optional on methods which are tagged as SEQUENTIAL or GUARDED. In general, all methods should have concurrency tags. |
| Java Usage Information | ||
@param parameter-name [WHERE (Expression)] Description |
Methods | Describes a method parameter. The description may
be continued on the following line(s). The expression indicates
restrictions on argument values. Restrictions that result in
exceptions, for example IllegalArgumentException, should
be indicated as such. In particular, it is important to indicate
whether reference arguments are allowed to be null.
There must be one @param tag for each and every
parameter to the method.
|
@return Description |
Methods | Describes a method's return value. The
description may be continued on the following line(s). If the method
being documented is a simple getter method (or similar), a
@returns tag is still necessary; however, in such a case,
the actual method description may be omitted (since the @returns
tag completely describes the method). |
@exception ExceptionClassName [IF (Expression)] Description |
Methods | Describes an exception which can be thrown by the
method, and the circumstances under which it is thrown. The exception
is linked to its class documentation. The guard indicates restrictions
on argument values. In particular, it is important to indicate
whether reference arguments are allowed to be null. There
must be one @exception tag for each and every exception
declared to be thrown by the method; in particular, if a
RuntimeException such as
IllegalArgumentException is declared in the method
signature, it must be documented. It is generally a good idea to
declare in the method signature any runtime exceptions which are
thrown as a result of conditions controllable at compile-time (such as
the method being called in the wrong system state, or a lack of sufficient
range checking on passed argument values).
|
| Versioning | ||
@version Version-String $ |
Classes, Interfaces | Denotes the version of the class. The text has no
special internal structure. A doc comment may contain at most one
@version tag. The @version tag normally
refers to the version of the software project which contains this
class, rather than the version of this particular class. |
@deprecated Reference to replacement API. |
All | Indicates that this API should no longer be used
(even though it may continue to work). By convention, the text describes
the API (or APIs) which replace the deprecated API. For example:
If the API is obsolete and there is no replacement, the
argument to |
@since version-tag |
All | Indicates the (release) version number in which
this feature first appeared. This version number, like that for
@version, is usually a project-wide version number rather
than a version number for the particular class in which the feature
appears. No @since tag is required for features which
have existed since the first version of the project. |
| Inheritance | ||
@hides FullClassName.FieldName [Description] |
Fields | Indicates that a particular field hides a
field in a parent class. For example:
|
@overrides FullClassName.MethodName() [Description] |
Methods | Indicates that a particular method overrides a method
in a parent class. For example:
If the overriding method does not either call or implement a superset
of the semantics of the method it overrides, its effects must be
documented (using precondition/postcondition/invariant tags and the
method description, as appropriate).
|
| Documentation | ||
@equivalent (Expression | Code Reference) |
Classes, Interfaces, Methods | Documents convenience or specialized methods which can be defined in terms of a few operations using other methods. |
@example Description |
All | Provides one or more examples of how to use a given class, interface, method, or field. This helps developers to quickly understand how to use your classes. |
@see APIName Label |
All | Adds a hyperlinked "See Also" entry to the class
documentation. APIName can be the name of a Java API or an HTML
anchor. Some examples (with their appearance in Javadoc in comments on
the right-hand side) are:
This Javadoc tag is often used to reference an external document which describes pertinent business rules or information relevant to the source code being documented. The character # separates the name of a class from the name of one
of its fields, methods, or constructors. One of several overloaded
methods or constructors may be selected by including a parenthesized
list of argument types after the method or constructor
name. Whitespace in
A doc comment may contain multiple |
{@link APIName Label} |
All | Adds an inline link to other documentation. This
tag begins and ends with curly braces to seperate it from the rest of
the inline text. It accepts exactly the same syntax for APIName
and Label as the @see tag. A doc comment
may contain multiple {@link} tags. |
| Design | ||
@design Description |
All | Provides information about design decisions you have made and/or useful things to know about parts of your code. |
| Serialization | ||
@serial Description |
Special |
Describes the purpose of and acceptable values for
a seriable field. This tag can only be used on default serializable
fields (instance fields, of classes which implement
Serializable, which are not declared to be
transient). There is no specific format for the
description. This information is used by Javadoc to build pages
describing the serialization behavior of the class. |
@serialField Field-Name Field-Type Description |
Special |
Documents an ObjectStreamField
component of the serialPersistentFields member of a
Serializable class. This tag can only be used for such
components, and one tag should be used for each. The "Field-Name" and
"Field-Type" fields should be the name and class of the field,
respectively; there is no specific format for the description. This
information is used by Javadoc to build pages describing the
serialization behavior of the class. |
@serialData Description |
Special |
Documents the sequences and types of data written
by the class's writeObject and/or
writeExternal methods as part of object
serialization. This tag can only be used in the doc comments for the
writeObject, readObject,
writeExternal, and readExternal
methods. This information is used by Javadoc to build pages describing
the serialization behavior of the class. |
| Dependencies | ||
@references (Expression) [Description] |
Classes, Methods, Fields | Indicates that the class or attribute references other constructs like objects, instances, files, etc. This is primarily used to indicate subtle interdependencies between classes, instances, etc. |
@uses (Expression) [Description] |
All | Indicates exactly which elements are utilized by this element. This tag is primarily used to indicate hidden dependencies. |
| Miscellaneous | ||
@guard (Expression) [Description] |
Methods | Indicates that actions use guarded
waits until the condition specified in
Expression holds. |
@values (Expression) [Description] |
Fields | Describes the possible values of a field, including ranges and/or distinct values. |
@complexity (Expression) [Description] |
Methods | Documents the time or space complexity of a method. Expression should be in big-O notation, but doesn't have to use proper Java syntax. E.g. O(n*n) and O(n^2) are equivalent, but the second is the more normal way to express a square term. Normally the free terms of the expression are documented in the description and are usually related directly to instance variables of the surrounding or related class. |
Always be as precise as reasonably possible in documenting effects.
A consistent code layout style improves code readability, maintainability, and robustness. We use xemacs for automatic code layout. Our code layout rules are as follows:
{") placement occurs at the beginning
of the next line of code in all cases (including empty blocks).
Code follows on the next line, indented by four spaces. The
xemacs code block provided below guarantees this indentation
behavior. For example:
for ( int i = 0; i < 100; i++ )
{
// this is where the code begins
a = i * i;
}
double x = ( y + z );
double a = ( Math.pow(x) * ( 1.23 + 4.56 ) ) * 2.0;
a += 3.1415;
x++;
boolean b = !( a == 1.0 );
for ( int x = 1; x < 100; x++ )
{
// do something
if ( x == 2 )
{
// a single line of code
}
while ( (x % 2) == 0 )
{
// multiple lines
// of code
}
switch ( x )
{
case 1:
{
// some code
}
default:
{
// more code
}
}
}
public,
protected, private.
The following elisp code expressions can be added to your
.xemacs/init.el startup file to institute all of the above
standards (except the brackets for every block of code in a
conditional or loop) automatically. Note that, in fact, it is
actually much safer just to take someone's working .xemacs/init.el
file and customize it for yourself. This way, subtle dependencies in
the setup are handled.
Here is the elisp code:
;; Indentation Settings
;; preload cc-mode to make settings
(require 'cc-mode)
;; indents are in blocks of two spaces
(setq-default c-basic-offset 4)
;; make sure we don't use tabs in indents
(setq-default indent-tabs-mode nil)
(cond ((or (string-match "4." c-version)
(string-match "5." c-version))
;; Setup for CC-mode version 4 and above.
;; Set up indention for programming in C, C++, Objective C, and
;; Java
(defun c-lineup-javadoc-comments (langelem)
;; Define a new custom indentation function for handling
;; Javadoc comments. Line up all first *'s. First create a
;; new context so the point, mark, and current buffer are not
;; munged, even in the case of abnormal exit.
(save-excursion
;; goto the point that is defining our indention depth
(goto-char (cdr langelem))
;; is it the first line of a javadoc comment?
(if (looking-at "/\\*")
;; yes! so return a 1
1
0)))
;; We define a new CC-mode style for our group's code standards.
;; We'll call this style "caltech-java".
(defconst caltech-java-style
'((c-basic-offset . 2)
(c-comment-only-line-offset . (0 . 0))
(c-offsets-alist .
((access-label . 0)
(arglist-close . c-lineup-arglist)
(arglist-intro . c-lineup-arglist-intro-after-paren)
(c . c-lineup-javadoc-comments)
(case-label . +)
(inher-cont . c-lineup-java-inher)
(inline-open . 0)
(knr-argdecl-intro . 5)
(label . +)
(statement-case-open . +)
(statement-cont . 0)
(substatement-open . 0)
(statement-block-intro . +)
(topmost-intro-cont . +)))))
;; Customizations for all c-mode, c++-mode, objc-mode, and java-mode.
(defun caltech-java-mode-hook ()
"Hooking in the Caltech Infospheres code standard for CC-mode
version 4 and turning on cc mode's minor modes."
;; Add caltech-java style and set it for the current buffer.
(c-add-style "caltech-java" caltech-java-style t)
;; Add any user-specific customizations here (should be none).
;;
;; CC Mode has two minor modes; auto-newline and hungry-delete.
;; If you don't like the behavior of either of these minor modes,
;; comment out the following expression. More information on
;; these minor modes is available in the CC Mode info pages.
(c-toggle-auto-hungry-state 1)
;; Keybindings for all supported languages can be added here.
;; We can upt these in c-mode-map because all the other maps
;; inherit from it.
;; (define-key c-mode-map <key> <func>)
)
;; Add hook to Java mode to start everything up everytime we
;; enter a Java buffer.
(add-hook 'java-mode-hook 'caltech-java-mode-hook))
((string-match "3." c-version)
;; Customization for CC-mode version 3.
))
The following elisp code expressions can also be added to your
.xemacs/init.el startup file to check your current xemacs buffer
according to the coding convention stated in this document by use of a customized
checkstyle tool.
Example:
int index = -1; // -1 serves as flag meaning the index isn't valid
Or, even better:
static final int INVALID= -1;
int index = INVALID;
| Element Type | Convention | Examples and Comments |
| Package | All lowercase | Use the recommended domain-based conventions
described in the Java
Language Specification, page 107 as prefixes. (For example,
com.otego.projectname.) |
| File | Compiler-enforced | The java compiler enforces the convention that file names have the same base name as the public class they define. |
| Class | Capitalize all subwords | DjinnMaster, BillTheCat, MyClass, PokerPlayer |
| Abstract Class | Same as Class, but starting with
Abstract |
AbstractDjinn, AbstractCat, AbstractClass, AbstractPlayer |
| Factory Class | Same as Class, but ending with Factory |
DjinnFactory, CatFactory, ClassFactory, PlayerFactor |
| Class Implementation | Same as Class, but either ending with Impl or be
prefixed with the a name which states its concrete implementation |
DjinnImpl, CatImpl, SiamCat, ClassImpl, MyClass, PlayerImpl, DefaultPlayer |
| Exception | Same as Class, but ending with Exception |
DjinnException, CatException, ClassException, PlayerException |
| Interface | Same as Class, it may have a Interface or
-able suffix |
DjinnInterface, CatInterface, Runnable, RemoteLoadable, Manager |
| Constant | All capital letters with embedded underscores | DJINN_MAX_WEIGHT, CAT_FUR_LENGTH, CLASS_SIZE, PLAYER_NUM_FINGERS |
| Instance Field | Initial letter is lowercase, all other subwords are capitalized. | DjinnName djinnName, BillTheCat bill, Class myClass, PokerPlayer aPlayer |
| Method | Initial letter is lowercase, remaining subwords are capitalized. | callDjinn(), kickCat(), twiddleClass(), pokePlayer() |
| Converter Method | Initial lowercase word is "to", remaining subwords are capitalized. | toGenie(), toTiger(), toAbstractClass(), toBridgePlayer() |
| Getters (methods that query state) | Initial lowercase word is "get", remaining subwords are capitalized and, if possible, are exactly the same as the name of the instance field to which they relate. | getDjinnName(), getCatColor(), getClassSize(), getPlayerBank() |
| Setters (methods that set state) | Initial lowercase word is "set", remaining subwords are capitalized and, if possible, are exactly the same as the name of the instance field to which they relate. | setDjinnLocation(), setCatSex(), setClassLoader(), setPlayerLuck() |
TestCase class for each
class of group of related classes. The TestCase
class should provide a unit test. These TestUnit classes should
be executed in the Ant build script to have consistent regression tests available.
TestCases for Avalon Components usually extend the
org.apache.avalon.excalibur.testcase.ExcaliburTestCase
class which creates an Avalon environment including a ComponentManager,
LogKit configuration, and Component Configuration for your Components.
The following are coding recommendations. It is not necessary to follow them to the letter, but we have found it helpful to always keep them in mind.
* form of import. Be
precise about what you are importing. Check that all declared
imports are actually used.
import at all (thus requiring that every class
reference be fully dot-qualified), which avoids all possible ambiguity
at the expense of requiring more source code changes if package names
change. (We, however, aren't that freaky.)
main() method should be separate from those containing
normal classes.
Cloneable and/or Serializable interfaces.
final only if it is a
subclass or implementation of a class or interface declaring all of
its non-implementation-specific methods (a similar principle applies
to the declaration of final methods).
final and/or comment conventions (see the
@modifies and @values tags) to indicate
whether instance fields, local fields and argument fields that never have
their values changed after
construction are intended to be constant (immutable) for the lifetime
of the object (as opposed to those that just happen not to get
assigned in a class, but could in a subclass).
protected to
private.
protected fields and methods is harder, since you
have to either loosen or check assumptions about their
properties. (Note that in Java, protected methods are
also accessible from unrelated classes in the same package. There is
hardly ever any reason to exploit this, though.)
get/set-style methods only when
they are intrinsic aspects of functionality.
protected access and update methods instead
(or sometimes public ones if they exist anyway).
@hides tag).
Type[] arrayName rather than
Type arrayName[].
static fields have
sensible values, and that non-private static methods can
be executed sensibly, even if no instances are ever created. Use
static intitializers (static { ... } ) if necessary.
Stack class, prefer
having two methods Object top() and void
removeTop() to having the single method Object
pop() that does both.
void unless they return
results that are not (easily) accessible otherwise. (i.e., refrain
from ever writing "return this;").
a.meth1().meth2().meth3()) can be sources of
synchronization problems and other failed expectations about the
states of target objects.
Object, Serializable or
Cloneable) and using conditionals which check
instanceof (or, reflectively,
isAssignableFrom()). Alternatives include techniques such
as double-dispatching or, often best, reformulating methods (and/or
their arguments) to remove dependence on exact argument type.
class Classifier
{
String identify( Object x )
{
return "object";
}
String identify( Integer x )
{
return "integer";
}
}
class Relay
{
String relay( Object obj )
{
return (new Classifier()).identify( obj );
}
}
public class App
{
public static void main( String [] args )
{
Relay relayer = new Relay();
Integer i = new Integer( 17 );
System.out.println(relayer.relay( i ));
}
}
@concurrency values for all public
methods. Describe the assumed invocation context and/or rationale for
existence or lack of synchronization. If you don't know the
concurrency semantics of your method, make it synchronized.
Object.equals(), also override
Object.hashCode(), and vice-versa.
readObject() and
writeObject() if a Serializable class relies
on any state that could differ across processes, including, in
particular, hashCodes and transient fields.
clone() may be called in a
class you write, then explicitly define it (and declare the class to
implement Cloneable).
clone()
might not do what you want (and, in fact, does not in most cases).
wait().
Class.newInstance().
abstract methods in base classes to those
with default no-op implementations. Also, if there is a common
default implementation, consider instead writing it as a
protected method so that subclass authors can just write
a one-line implementation to call the default.
abstract methods, avoiding problems which occur
when they forget to do so but should have.
equals instead of
operator == when comparing objects. In particular, do not
use == to compare Strings.
equals method to
compare objects, then they want you to use it. Otherwise, the default
implementation of Object.equals() is just to use
==.
suspend()/resume() pairs to implement
synchronization with threads.
suspend() and resume() are
inherently fragile, and have even been deprecated by JavaSoft as of JDK 1.2.
wait() calls in while
loops which re-wait if the condition being waited for does not hold.
wait() wakes up, there is no
guarantee that the condition it is waiting for has become true.
notifyAll() instead of notify().
notify() can normally
only support at most one kind of wait condition across all methods in
the class and all possible subclasses.
null to any reference variable which is no
longer being used. This includes, especially, elements of arrays.
=") inside if
and while conditions.
=" should have been
"==", except when the variable is a
boolean.
int unused = obj.methodReturningInt (args);
catch for all
unchecked exceptions that can be dealt with.
java.util.NoSuchElementException. Declare and catch them
anyway. It'll make your code more robust.
C cx = null;
if ( x instanceof C )
{
cx = (C) x;
}
else
{
evasiveAction();
}
ClassCastException.
All our projects are build by Ant
You'll find a distribution in the Distribution Section of the Otego Intranet site.
Two primary supported free implementations of Emacs exist:
Extending Emacs. (X)Emacs is extended through the use of Emacs LISP packages. The primary packages we use for the development of Java are as follows (this list is by no means complete and reflects our personal biases):
The JDE supports both Emacs (Unix and Windows versions) and
XEmacs. It is freely available under the GNU public license.
(Ed. note --- note that much of the functionality of
JDE is simply JDE using other packages like cc-mode,
font-lock-mode, etc. It does pull all of these packages
together very well.)
Briefly, using tags with Java means that your emacs knows the location and completion of all interesting features (classes, interfaces, fields, methods, etc.) of your project so that you can (a) jump right to the feature definitions, (b) use completion (see the next bullet), (c) do regular expression searches and/or replaces on tags (e.g. global replace of a variable), and more. See the documentation on tags in Emacs info for more information on the use of tags.
turn-on-fast-lock and related
functions), Lazy Font Locking (see lazy-shot-mode),
caching font lock information (see
fast-lock-cache-directories), and more.