01 / 20

Code Organization
in Java

Learn how to structure classes and methods for maximum readability, maintainability, and cohesion in your Java programs.

Java

What is Code Organization?

Code organization is the practice of structuring your source files, classes, and methods so that your program is easy to read, understand, and modify. It's the difference between a messy drawer and a well-labeled filing cabinet.

Key Terms to Know

Readability
How easily a human can read and understand code: naming, formatting, and logical flow.
Cohesion
The degree to which elements inside a class or method belong together and serve a single purpose.
Coupling
How dependent one class is on the internals of another. Low coupling means classes can change independently.

Why Organization Matters

Disorganized Util.java Helper.java DoStuff.java Misc.java X.java Organized App.java User.java Order.java UserDAO.java OrderDAO.java

The Single Responsibility Principle

The most important rule of code organization: every class should have exactly one reason to change. This means each class encapsulates one concept, one feature, or one layer of logic.

Anatomy of a Well-Organized Class

BankAccount.java 1. Constants + Static Fields 2. Instance Fields (private) 3. Constructors 4. Public Methods (API) 5. Private Helper Methods 6. toString, equals, hashCode ★ ★ ★ ★ ★ ★ ↓ Reading order

Cohesion vs. Coupling

High Cohesion ✓ High Coupling ✕
Definition Methods in a class serve one purpose Classes depend heavily on each other's internals
Goal Maximize Minimize
Effect on Changes Edits stay local to one class One change cascades through many files
Example Calculator class: add, subtract, multiply UI class directly reads database fields
Testing Easy to test in isolation Requires complex setup to test

How to Organize Your Code

1
Identify responsibilities. List everything your class currently does. If you find more than one core job, plan to split.
2
Group related methods. Methods that operate on the same data or serve the same feature belong in the same class.
3
Name classes by noun, methods by verb. UserValidator, OrderService for classes. validate(), calculateTotal() for methods.
4
Order members consistently. Follow the standard order: constants, fields, constructors, public methods, private helpers.
5
Keep methods short. A method longer than 20 lines often signals that it should be broken into smaller helper methods.

Example: Before Refactoring

public class StudentManager { // Calculates grade, prints report, AND saves to file public void processStudent(String name, int[] scores) { double avg = 0; for (int s : scores) avg += s; avg /= scores.length; String grade = avg >= 90 ? "A" : avg >= 80 ? "B" : "C"; System.out.println("Report: " + name + " - " + grade); // ... 50 more lines writing to a file } }

Example: After Refactoring

public class GradeCalculator { public String calculateGrade(int[] scores) { double avg = Arrays.stream(scores).average().orElse(0); return avg >= 90 ? "A" : avg >= 80 ? "B" : "C"; } } public class ReportPrinter { public void print(String name, String grade) { System.out.println("Report: " + name + " - " + grade); } } public class ReportSaver { public void saveToFile(String name, String grade) { // File writing logic only } }

Organizing Methods Within a Class

public class ShoppingCart { // --- Constants --- private static final double TAX_RATE = 0.08; // --- Fields --- private List<Item> items; // --- Constructor --- public ShoppingCart() { this.items = new ArrayList<>(); } // --- Public API --- public void addItem(Item item) { items.add(item); } public double getTotal() { return subtotal() + tax(); } // --- Private helpers --- private double subtotal() { /* ... */ } private double tax() { return subtotal() * TAX_RATE; } }

Organizing with Packages

com.myapp model User.java Order.java service UserService.java OrderService.java ui MainView.java Menu.java model: Data classes (POJOs, entities) service: Business logic and rules ui: User interface and display

The Short Method Principle

A method should do one thing and be short enough to understand at a glance. If a method has more than one level of abstraction, extract the lower-level details into helper methods.

5-20 lines
Ideal method length. Easy to read, test, and name descriptively.
20-40 lines
Acceptable but review carefully. Could it be split?
40+ lines
Almost certainly needs refactoring. Hard to test and debug.

Naming Conventions

Element Convention Example
Classes PascalCase, noun ShoppingCart
Methods camelCase, verb calculateTotal()
Variables camelCase, descriptive totalPrice
Constants UPPER_SNAKE_CASE MAX_RETRIES
Packages all lowercase com.myapp.model

Common Mistakes

✕ God Class
One class that does everything: database, logic, UI. Impossible to test or maintain.
✕ Vague Names
Names like Manager, Helper, or Util signal unclear responsibility. Be specific.
✕ Mega Methods
Methods over 50 lines with nested loops and conditionals. Extract smaller methods.
✕ Random Ordering
Mixing public and private methods randomly. Readers can't predict where to look.

Question 1 of 5

A class called StudentManager calculates grades, prints reports, and saves data to a file. Which principle does this violate?

Question 2 of 5

In a well-organized Java class, what should appear immediately after the instance fields?

Question 3 of 5

Which of the following class names best follows Java naming conventions and signals clear responsibility?

Question 4 of 5

A method is 65 lines long with three nested loops. What is the best refactoring approach?

Question 5 of 5

Which package structure best demonstrates separation of concerns for a web application?