Class Structure

About

Class structure refers to the standardized layout and organization of elements inside a Java class — such as fields, constructors, methods, and nested types. A clean, consistent class structure significantly improves readability, maintainability, and navigability for all developers working on the codebase.

Following a predictable structure ensures that anyone reviewing or maintaining the code can quickly understand its purpose and behavior without unnecessary scanning or confusion.

Importance of Consistent Class Structure

  • Improves Readability: Readers know where to look for fields, constructors, and logic.

  • Supports Maintainability: Makes future refactors safer and faster.

  • Encourages Logical Separation: Helps prevent mixing unrelated concerns in one place.

  • Simplifies Code Review: Clear layout reduces the mental effort needed to understand changes.

  • Promotes Consistency: Across modules, teams, and contributors.

A typical Java class should follow this structure (each section separated by a blank line):

1. Class-level Javadoc / annotations
2. Constant fields (static final)
3. Static fields
4. Instance fields
5. Constructors
6. Public methods
7. Protected methods
8. Private methods
9. Getters and setters (if applicable)
10. Inner/nested types (if any)

Class-Level Guidelines

1. Class Declaration

  • Use meaningful names that reflect the class responsibility.

  • Add class-level JavaDoc for public and core classes.

  • Apply annotations (@Service, @Component, etc.) before the class.

2. Constants First

All static final constants should come first, grouped and optionally commented.

3. Static Fields and Initializers

Next come non-final static fields (if any), e.g., Logger or shared caches.

4. Instance Variables (Fields)

  • Declare private by default.

  • Use clear naming (userRepository, cacheService).

  • Group by type or functionality (e.g., dependencies together, configuration together).

5. Constructors

  • Use constructor injection in Spring for mandatory dependencies.

  • Avoid logic in constructors other than field assignment.

6. Public Methods

Public methods are typically business methods (e.g., generateToken(), validateToken()).

  • Group logically (e.g., CRUD operations together).

  • Add JavaDoc if the behavior is non-obvious.

  • Keep method size small and cohesive.

7. Protected Methods

Use for extensibility if necessary. For abstract or base classes, put template methods here.

8. Private Methods

Used to encapsulate helper or breakdown logic. Place private methods after the public logic they support (top-down readability).

9. Getters and Setters

If using Lombok, prefer @Getter, @Setter, or @Data only where needed. Otherwise, place them at the bottom unless part of an interface contract.

10. Inner Classes / Enums / Interfaces

If needed, place them at the end of the file. Use sparingly, and only if tightly coupled with the outer class.

Example

Last updated