My Java Code Conventions

Although I am able to adapt to another code convention when working on a group project, I’m very picky when it’s for a personal project.

120 characters per line

And that’s approximate. If an extra 20-30 characters will prevent you from

The 80 characters per line convention is, in my opinion, stupid. It’s too short. We have huge monitors now, and honestly, IBM’s 80 column punch card from 1928 is so outdated I can’t even bother.

Linus conveys why pretty well in this message: https://lkml.org/lkml/2020/5/29/1038

The structure

  1. 1 empty line at the beginning of the class
  2. All constants are at the top of the class
  3. 1 empty line after the constants
  4. All instance variables
  5. All constructors, starting from the one with the most parameters
  6. All methods

Here’s an example:

public class SomeClass {

    public static final int SOME_CONSTANT = 1000;
    public static final int SOME_OTHER_CONSTANT = 2000;
    public static final int SOME_MORE_CONSTANT = 3000;

    private int age;
    private String name;

    public SomeClass(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public SomeClass() {}

    public int getAge() {
        return age;
    }

    public int setAge(int age) {
        this.age = age;
    }
}

Package names: Alphanumeric only

No underscore either, please.

Constant name

Yeah, you know it. All uppercase with an underscore between each word.

e.g.: MINUTES_PER_HOUR

Class name: PascalCase

e.g.: ApplicationManager

Variable and method name: camelCase

e.g.: getCookies(), chocolateChipCookies

Space between if/else/for/do/try/catch/while and parenthese

To be honest, this wouldn’t bother me that much if it was consistent, but most of the time, it isn’t. One line, it’ll be if(…), the other, it’ll be if (…). The worse enemy of a programmer is inconsistency. It’s not too hard to get used to how one person programs, but if that person can’t make up his mind and stick with one way of programming, it gets exponentially more difficult.

try {
    do {
        if (…) {
            …
        } else {
            …
        }
    } while (true);
} catch (Exception e) {
    …
}

TABS for indentation, SPACE for alignment

Why tabs? Because if one of your coworkers wants to see 2 spaces, he can set his IDE to show two space, most code editors have that feature too. Likewise, if he wants to see 4 spaces, then he can do the same. Using TABS accommodates everybody’s tastes.

When to use {}: ALWAYS

// Perfect
if (true) {
    doSomething();
} else {
    doSomethingElse();
}

// Ok
if (true) { doSomething(); }

// Bad
if (true)
    doSomething();
else
    doSomethingElse();

// Bad
if (true) doSomething();
else doSomethingElse();

// Meh
if (true) { doSomething(); }
else { doSomethingElse(); }

Comments

// This is a comment, so there's a space after "//"
//String someVar = "This is commented code, so there's NO space after //";