Canonical Form

When a Java programmer declares a class, he follows certain patterns that make his class easier for others to read and use. Together, these patterns are called the canonical form.

Style

A Java programmer follows the Java coding conventions. These conventions dictate the layout of the code.

Comments

A Java programmer places Javadoc comments above the class declaration and every public member.

Fields

Fields are generally private.

Constructors are provided to initialize all fields.

Consider providing every field with an accessor and mutator method.

Consider providing refence fields with delegator methods instead.

See Canonical Form for Fields for details.

Overrides

Consider overriding the following methods inherited from the Object class:

toString- useful for debugging and for

equals- if logical and literal equality are different

hashCode- required if equals has been redefined.

Interfaces Implemented

Consider implementing the following interfaces:

Serializable—for objects containing application data that needs to be saved to files.

Cloneable- for value objects that can be copied without worying about synchronization bugs

Comparable<T>- for objects that need to be compared with each other

Example: Canonical Form for Reference Objects

The Document Class

Example: Canonical Form for Value Objects

The Rational Class

Testing

Every class should have at least one test case class.

For example:

class TestRational {
   public static main(String[] args) {
      Rational r1 = new Rational(3, 4);
      Rational r2 = new Rational(1, 2);
      Rational actualSum = r1.add(r2); // 1/2 + 3/4
      Rational expectedSum = new Rational(5, 4); // 5/4
      System.out.println("pass = " + actualSum.equals(expectedSum));
   }
}

In general, it's better to use a testing framework like JUnit to create and run test cases.