Our interfaces are distinguished from classes by appending
"Ifc" or "able". We use javadoc comments before each class and
method (unless they are short and obvious). We terminate them
with "**/"
for symmetry with the "/**"
that must start a javadoc comment.
The sample code shown below illustrates the code styling we
use for the remainder of this book. Each distinct code section,
such as a method or an if-else
statement, is indented to the right from the section in which
it is nested. All primitive variables are initialized explicitly.
(Default values would be assigned automatically but by initializing
them you make clear that the values given are what you intended
for those variables.)
For the class definition and for long methods we put the name
in a comment after the final brace. (We use "//
ctor" for long constructors.)
//
Non javadoc comments, authorship, and
// class development history.
package javatech.xxx.yyy.zzz;
import java.io.*;
/** javadoc comments about the class. **/
public class SomeClassName
{
int fInstanceVal = 1;
double fVal = 0;
Integer fInstanceRef;
public SomeClassName {
... constructor code ...
} // ctor - for longer constructors
/** Describe the method. **/
public void methodName (...) {
int x = 5;
some_method (x);
if (test) {
do_something ();
}
else {
...
}
...
try {
xxx ();
}
catch (Exception e) {
handle_it ();
}
} // methodName - for longer methods
/** Longer comment.
* - this asterisk is ignored by javadoc
**/
public void someMethodWithLotsOfParameters
(
int param1,
int param2,
etc.
) throws SomeException {
...
} // someMethodWithLotsOfParameters
/** Private method names with underscores.
**/
private void some_method (int i) {
...
} // some_method
/** Getter method. **/
double getVal () {
return fVal;
}
/** Setter method. **/
void setVel (double val) {
fVal = val;
}
} // class SomeClassName |
The getVal()
and setVal()
are examples of the common getter and setter methods use to
get and set the value of a particular variable whose name is
included in the method name. In this way we follow the important
JavaBeans
standard although the use of JavaBeans is not discussed here.
We also note that the consistent use of the fMemberVariable
notation for member variables and local_variable_name
notation for local variables inside a method makes it impossible
to accidentally shadow a member variable with a local
variable
Note: Shadowing occurs when a
subclass has a data field or local variable with the same name
as that of a data field in a super class. This is almost never
useful and should be avoided.
References and Web
Resources