Java Programming Style
General advice on how to make your program more readable and less
error-prone:
- every class should be in a separate file;
- use meaningful names for the variables and for the file names;
- use comments;
-
comments should explain what a piece of code intends
to do; in particular, every method -- even a simple one -- should, as a minimum, have comments explaining what
exactly it does, and what is the meaning of all its parameters
- comments should not duplicate the text of the program; for example,
"initialize the variables" is a good comment, but a comment "assign the
value 0 to the variable x" after a line x = 0; does not add any
additional meaning to the code;
- always use {} for blocks corresponding to "if", "while", and "for"
statements, even if the corresponding block consists of only one
statement;
- use indentation;
- every time you have a method within a class, a group of statements
within an if-else construction or a loop -- anything with {} --
indent this group of statements;
- do not indent too much, since then you will run out of space; Java
recommends 4 spaces; our textbook often uses 3; 2 spaces is also OK;
- try not to use Tab because Tab may look different on different
screens and different editors -- especially if you sometimes use Tab
and sometimes, simply add a few blank spaces;
- avoid long lines since they're not handled well by many terminals.
In general, follow the style of the examples from the textbook. For
a detailed description of the official Java recommendations,
click here.