CodeGym /Courses /JAVA 25 SELF /Code style and readability, code conventions

Code style and readability, code conventions

JAVA 25 SELF
Level 23 , Lesson 4
Available

1. Introduction

In programming, style is not about fashion — it’s about survival. Java is a language used by huge teams, and if everyone writes “the way they’re used to,” the project quickly turns into a set of disjointed pieces that only the author can understand (and not always even them).

Code style is a set of rules that make code equally readable for everyone. It’s like road signs: if you ignore them, traffic quickly turns into chaos.

Why is this important?

  • Readability: people read code more often than they write it. Bad style is like a doctor’s bad handwriting: no one will understand what’s written there.
  • Maintainability: if code is written by the rules, it’s easier to change, with less chance of accidentally breaking something.
  • Collaboration: in a team, everyone should understand each other without unnecessary questions.
  • Tools: autoformatters and code analyzers work better when the style is consistent.

2. Common code style mistakes (and how to avoid them)

Inconsistent indentation and braces

Mistake:
Code without indentation and with chaotic braces is painful for the eyes and brain.

if(x>0){
System.out.println("x is positive");
}else{
System.out.println("x is not positive");
}

How it should be:

if (x > 0) {
    System.out.println("x is positive");
} else {
    System.out.println("x is not positive");
}

Comment:
Use four spaces for each level of nesting (that’s the Java standard). Tabs are evil unless the whole team agrees otherwise.

Poor names for variables, methods, and classes

Mistake:

int a = 5;
String s = "John";
void f() { /* ... */ }

How it should be:

int age = 5;
String userName = "John";
void printReport() { /* ... */ }

Comment:
Names should be meaningful and reflect the essence of the variable or method.

  • Classes — start with an uppercase letter, CamelCase: UserAccount.
  • Methods and variables — start with a lowercase letter, camelCase: calculateSalary, userList.

Overly long methods and classes

Mistake:
A 100-line method, a 1000-line class — a true nightmare mode for maintenance.

How it should be:
Each method should do one thing and be short (ideally — fit on a screen). Classes also shouldn’t grow to the size of “War and Peace”.

Example:

Bad:

public void processOrder() {
    // 200 lines of code
}

Good:

public void processOrder() {
    validateOrder();
    calculateTotal();
    saveToDatabase();
    sendEmailConfirmation();
}

Using “magic numbers” and strings

Mistake:

if (status == 42) {
    // ...
}

How it should be:

public static final int STATUS_APPROVED = 42;

if (status == STATUS_APPROVED) {
    // ...
}

Comment:
Instead of “magic” numbers and strings, use constants (static final). In newer versions of Java you also have enum — use enums for limited sets of values.

Comments: missing or excessive

Mistake 1:
No comments at all — it’s unclear what complex code does.

Mistake 2:
Comments for every action, even the obvious ones.

// Increment x by 1
x = x + 1;

// Check if x equals 10
if (x == 10) {
    // ...
}

Such comments only get in the way! Comment only complex or non-obvious parts. Ideally, good code should be understandable without comments — comments should explain “why”, not “what”.

// Apply discount for VIP customers
double total = calculateTotalWithDiscount();

3. Java conventions: how professionals write

Java has official and de facto code style standards. Oracle Java Code Conventions and the Google Java Style Guide are the most popular.

Indentation and braces

The opening curly brace is placed on the same line as the declaration:

public void print() {
    // ...
}

Indentation — four spaces per level.

Naming

  • Classes and interfaces: CamelCase starting with an uppercase letter (Person, UserAccount).
  • Methods and variables: camelCase starting with a lowercase letter (calculateSalary, userList).
  • Constants: ALL_CAPS_WITH_UNDERSCORES (MAX_SIZE, DEFAULT_TIMEOUT).
  • Packages: lowercase only, dot-separated if needed (com.example.project).

Spaces

Spaces around operators and after commas:

int sum = a + b;
System.out.println(name, age);

Do not put a space after an opening and before a closing parenthesis:

if (x > 0) { ... }

Line length

It’s recommended to keep lines under 100–120 characters. (Yes, your monitor is huge, but code still reads better when it doesn’t run off to the right.)

Order of class members

Recommended order (per Oracle):

  1. Fields (static first, then instance)
  2. Constructors
  3. Methods

Example:

public class User {
    private static int userCount;
    private String name;

    public User(String name) {
        this.name = name;
        userCount++;
    }

    public String getName() {
        return name;
    }
}

4. Example: refactoring bad style

Here’s a class you may encounter in the wild:

class person{String n;int a;void p(){System.out.println(n+" "+a);}}

Somewhere in an office, a Java developer is crying because of this code.

Let’s improve it:

public class Person {
    private String name;
    private int age;

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

    public void print() {
        System.out.println(name + " " + age);
    }
}

What changed:

  • Class and members with proper access modifiers.
  • Meaningful, readable names.
  • Each class member starts on a new line.
  • Uses a constructor for initialization.
  • Fields are private to preserve encapsulation.

5. Useful tips

Autoformatters

Modern IDEs (IntelliJ IDEA, Eclipse, VS Code) can automatically format code according to a standard.

Hotkeys:

  • IntelliJ IDEA: Ctrl + Alt + L
  • Eclipse: Ctrl + Shift + F

Static analysis

Tools like Checkstyle, SonarLint, and PMD help detect style violations and potential errors even before you run the program.

What it looks like:

  • Checkstyle complains if you name a variable x instead of userAge.
  • SonarLint will point out if a method is too long or a class violates SOLID principles.

Separation of concerns and “clean” code

  • Each class should be responsible for only one task (Single Responsibility Principle).
  • Don’t be afraid to create additional classes and methods — that’s not “bloat,” it’s care for the future reader.
  • Avoid code duplication: if you see two similar fragments, extract them into a separate method.

Constants and “magic numbers”: the right way

Instead of:

double price = 100 * 0.18;

Better:

public static final double VAT_RATE = 0.18;
double price = 100 * VAT_RATE;

And if you often have fixed sets of values — use an enum:

public enum Status {
    NEW, IN_PROGRESS, DONE
}

6. Typical mistakes in code style and readability

Error #1: Ignoring code conventions.
If the team doesn’t have a unified style, the code quickly becomes unreadable and hard to maintain. Even if you code alone, a year from now you’ll thank yourself.

Error #2: Names that are too short/too long.
A variable like a or temp is bad. A variable like theCurrentUserNameThatIsUsedForAuthorizationInTheSystem — also don’t. Find a balance: userName, age, bookList.

Error #3: “Magic numbers”.
Inserting numbers and strings directly into the code hinders maintenance and increases the likelihood of errors.

Error #4: Huge methods and classes.
The larger the method, the harder it is to test and understand. Break it into logical parts.

Error #5: Poor class structure.
Fields are scattered anywhere, methods are declared in random order — all this makes it harder to quickly find what you need.

Error #6: Excessive or missing comments.
A comment like “variable initialization” next to int x = 0; isn’t needed. A comment explaining complex business logic is very much needed.

Error #7: Inconsistent formatting.
In one part of the project — four spaces, in another — tabs; here braces on a new line, there — on the same line. It looks sloppy and annoys teammates.

1
Task
JAVA 25 SELF, level 23, lesson 4
Locked
Tidying up messy running code 🧹
Tidying up messy running code 🧹
1
Task
JAVA 25 SELF, level 23, lesson 4
Locked
Clear names for a clearer system 💬
Clear names for a clearer system 💬
1
Task
JAVA 25 SELF, level 23, lesson 4
Locked
Tax rate: No more "magic numbers"! 💸
Tax rate: No more "magic numbers"! 💸
1
Task
JAVA 25 SELF, level 23, lesson 4
Locked
Ideal structure for your product 📦
Ideal structure for your product 📦
1
Survey/quiz
OOP — typical mistakes, level 23, lesson 4
Unavailable
OOP — typical mistakes
OOP — typical mistakes
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION