Clean code in Java
Oracle’s code conventions for Java, last revised in 1999: classes are nouns in mixed case, methods are verbs starting lowercase, constants in capitals, 4 spaces a level, lines under 80 characters.
What does Oracle’s code conventions ask for?
Variable names should be short yet meaningful. […] One-character variable names should be avoided except for temporary "throwaway" variables.
source
From Oracle, Java naming conventions. Oracle no longer updates these pages source; last revised in 1999 source.
How are names written in Java?
| Kind | Example | Rule |
|---|---|---|
| Types | ShoppingCart | Classes are nouns in mixed case, each word capitalised. source |
| Functions | addItem | Methods are verbs in mixed case, first letter lowercase. source |
| Variables | itemCount | Variables in mixed case with a lowercase first letter. source |
| Constants | MAX_ITEMS | Constants in capitals with underscores. source |
What does cleaner Java look like?
class loanmgr {
static final int maxdays = 14;
boolean chk(Loan l) {
int d = l.daysOut();
if (d > maxdays) return true; else return false;
}
}class LoanPolicy {
static final int MAX_LOAN_DAYS = 14;
boolean isOverdue(Loan loan) {
return loan.daysOut() > MAX_LOAN_DAYS;
}
}Other languages
More on clean code: comments, functions, naming and the checklist.