Readable and Reusable Code
When you write code, you must take care that your code will be easy to
maintain.
To achieve this goal, your code must in particular be readable and easy
to reuse.
Here are some rules you may follow in that aim :
You must follow the practices followed by the programmers using the
same laguage. In Java, that means that you must resepect the code conventions
defined by Sun. We present here the main elements of this document :
- Identifiers, except for constants, are composed by words
separated using capitals, for example :
car
, carWithDriver
.
Identifiers for constants use only capitals, words being separated by
undescores, for example : PI
, LIGHT_SPEED
.
- Identifers for variables and methods start with a small lettre,
like
car
, carWithDriver
, kilometers()
.
- Identifiers for classes start with a capital :
Shape
,
ArrayList.
- Each line should contain at most one statement.
- The opening brace should be at the end of the line that begins
the compound statement. The closing brace are usually alone on their
line, except before an
else
or a catch
.
- Keywords before a variable or a method must allways follow the
same order. The recommanded order is :
<access control> <static>
<final>
<native><synchronized> <type>
- Names of packages use small letters :
graph
, graph.algorithm
.
Interfaces and implementations must be clearly separated.
The visibility of a variable, method or class must be limited to its
use.
You must always avoid code duplication.
The name of an identifier must be meaningful or usual.
Commentaries must explain the code and how to use it, not rephrase it.