Idioms

A.k.a. how not to speak Java with an accent.

Programming is about expressing ideas clearly

If we only cared about computers, we’d write everything in machine code or assembly.

Assembly

Code to add two numbers.

; 0F4:       4801FA           ADD RDX, RDI
; 0F7:       488BC2           MOV RAX, RDX
; 0FA:       48D1E0           SHL RAX, 1
; 0FD:       7009             JO L0
; 0FF:       48D1E2           SHL RDX, 1
; 102:       488BE5           MOV RSP, RBP
; 105:       F8               CLC
; 106:       5D               POP RBP
; 107:       C3               RET
; 108: L0:   CC54             INT3 84
; 10A:       0A               BYTE #X0A
; 10B:       CC10             INT3 16

Write your code for humans

Variable names

Variable name length

The broader the scope of a variable, the longer the name.

Method parameters

Method parameters are technically only used within the method but they also form part of the documentation of the method so it’s good to use a name that describes what the argument is.

Compare

public int[] numberTable(int num)

and

public int[] numberTable(int size)

Which tells you more about how the argument is going to be used?

Every method gets its own variables

There’s no need to come up with different parameter names for different methods.

In fact, if you have several methods that take arguments with the same meaning, it’s good to use the same names in each method, e.g. red and spotted in the boolean birds methods.

 public boolean isFlobbyBird(boolean red, boolean spotted) {

 public boolean isBloggyBird(boolean red, boolean spotted) {

Loop variables

Tend to be the shortest, often only one letter.

When in doubt use i.

for (int i = 0; i < array.length; i++) {

Definitely if the loop variable is being used as an index into a String or array.

Some exceptions

If the loop variable is being used as something other than an index, it’s okay to use a different name, probably still one letter:

for (int n = 2; n < max; n++) {

Suggests than n is just an arbitrary number.

Why it matters

As with consistent code formatting, using consistent naming patterns makes your code easier to read because deviations from the pattern can be used to draw attention to code that is different.