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.
A Java programmer follows the Java coding conventions. These conventions dictate the layout of the code.
A Java programmer places Javadoc comments above the class declaration and every public member.
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.
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.
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
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.