Java class definition: Programmer Checklist
A great book on improving the quality of your Java is Effective Java by Joshua Bloch.
Below, a few suggestions are given, primarily concerned with the definition a single class (i.e., the suggestions are not about object-oriented design). This check list is not exhaustive.
- Minimize accessibility
(Java tutorial on accessibility of class members)
- Class acessibility:
- If class B is used only by class A, make B an inner class of A.
- If it is a top-level class: Prefer package-private to public.
- Attribute accessibility: Declare all attributes private.
- Method accessibiltiy:
- Prefer private to package-private.
- Prefer package-private to protected.
- Prefer protected to public.
- Local variable accessibility: Minimize the scope of local variables.
- Class acessibility:
- Minimize mutability
- If possible, make the class immutable.
- If it cannot be immutable, minimize the set of attributes that can be modified after it is constructed. Declare final those attributes that are set only when the object is constructed.
- If it is not extended, declare the class final.
- If the class is extended, for each method, if it is not overriden in a subclass, declare it final.
- Declare non-primitive method parameters final.
Prefer
ImageModel getMinImageModel( final List<ImageModel> imageModelList ) { ... }
ImageModel getMinImageModel( List<ImageModel> imageModelList ) { ... }
- Maximize readability
- All team members should agree on, and adhere to, a set of coding conventions.
- Use semantically meaningful names.
Typically:
- A class name is a noun phrase.
- An attribute name is a noun phrase, although its values may be adjectives (e.g., red).
- A method name has a structure <verb><noun phrase> (e.g., getSaveMenuItem).
- Declare the type of a local variable where it is first used.
- Reusability
- Declare the interface, construct the class. For example, prefer
List<ImageModel> focusImageModel = new LinkedList<ImageModel>();
LinkedList<ImageModel> focusImageModel = new LinkedList<ImageModel>();
- Declare the interface, construct the class. For example, prefer
-
Always override the toString method.
Your implementation should, for each attribute (with perhaps a few exceptions), invoke its toString.
For example,
/** Provides a String representation of the
Task
. * @return a String representation of theTask
: * */ public String toString () { StringBuffer taskString = new StringBuffer(); taskString.append( getClass().getName() ).append(" "); taskString.append( taskId.toString() ); taskString.append( ": $unsetArgs: " ).append($unsetArgs).append(" "); if ( inputs == null ) { taskString.append( "NONE ").append( getClass() ).append( " " ); } else { for ( int i = 0; i < inputs.length; i++ ) { taskString.append( i ).append( ": " ); if (inputs[i] == null ) { taskString.append( "null " ); } else { taskString.append( inputs[i].toString() ); } } } return new String ( taskString ); }