cleancode.in

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 should Java code look?

  • Four spaces a level. source
  • Lines of 80 characters at most. source

How are names written in Java?

KindExampleRule
TypesShoppingCartClasses are nouns in mixed case, each word capitalised. source
FunctionsaddItemMethods are verbs in mixed case, first letter lowercase. source
VariablesitemCountVariables in mixed case with a lowercase first letter. source
ConstantsMAX_ITEMSConstants in capitals with underscores. source

What does cleaner Java look like?

Before
class loanmgr {
    static final int maxdays = 14;

    boolean chk(Loan l) {
        int d = l.daysOut();
        if (d > maxdays) return true; else return false;
    }
}
After
class LoanPolicy {
    static final int MAX_LOAN_DAYS = 14;

    boolean isOverdue(Loan loan) {
        return loan.daysOut() > MAX_LOAN_DAYS;
    }
}

What changed?

  • The class is a noun in mixed case: LoanPolicy. source
  • The method is a verb starting lowercase: isOverdue. source
  • The constant is in capitals. source
  • No one letter names: l and d were not loop counters. source
  • The if that returned true or false is now the comparison.