Java Class Design Hints: Writing Clean, Maintainable Classes
Seven practical rules for designing Java classes: keep data private, initialize everything, replace primitive clusters with classes, skip needless getters and setters, split classes with several responsibilities, choose good names, and prefer immutability, illustrated with records and enums.
kvi5hnuCode Sprout team member9 min readOn this page
Part 4 covered how classes work: fields, constructors, methods, static members, records, packages and documentation comments. Knowing the mechanics doesn't automatically produce good classes, though. This closing article collects seven design guidelines that make classes easier to use, change and trust. Treat them as defaults you depart from deliberately, not as laws; they are also what code reviewers tend to check first.
1. Keep Fields Private
Private fields are the foundation of encapsulation, and the exceptions are few. Even when callers need a value, give them a method rather than the field.
The reason is practical: how data is stored changes far more often over a program's life than what callers do with it. Private fields mean that:
- you can change the storage without touching any code outside the class, and
- when a field holds a wrong value, the only suspects are the class's own methods.
(public static final constants are the standard exception, and records expose their components on purpose. See encapsulation.)
2. Initialize Every Field Deliberately
The compiler refuses to read an unassigned local variable, yet it quietly fills fields with 0, false or null. Don't build on those defaults. Give every field a value on purpose, with an initializer or in each constructor:
public class ShoppingCart {
private final List<Item> items = new ArrayList<>(); // never null
private String couponCode = ""; // or Optional, but never an accidental null
private final Instant createdAt;
public ShoppingCart(Clock clock) {
createdAt = clock.instant();
}
}
Forgotten initialization is a leading cause of NullPointerException. Declaring fields final helps: a constructor that forgets one no longer compiles.
3. Group Related Primitive Fields into Their Own Type
When several basic-type fields only make sense together, they are a type waiting to be named. An Order class like this one
private String shipStreet;
private String shipTown;
private String shipRegion;
private int shipPostcode;
is better off with an Address:
record Address(String street, String city, String postalCode, String countryCode) { }
record Order(String id, Address shipTo) { }
Now changes to addresses, such as supporting international addresses (postal codes with letters, regions instead of states, a country code), happen in one place. Address can be reused by Customer, Supplier and Warehouse, and validated once. (Notice that int shipPostcode was a mistake anyway: postal codes like 02134 lose their leading zero as numbers, and many countries use letters.)
The same idea applies to single values with meaning, sometimes called value objects: Money(BigDecimal amount, Currency currency) instead of a bare double price, or EmailAddress instead of String. Overusing primitives is known as the "primitive obsession" code smell.
4. Expose Operations, Not Every Field
Some fields need both a getter and a setter, like a salary that changes. Others should never change after construction, like the date someone started. And some are pure implementation detail that no caller should see at all, such as a cache or a lookup table the class uses internally.
Don't generate a getter and a setter for every field by reflex. Expose meaningful operations (giveRaise(4), ship(order), addItem(item)) and only the read access callers actually need.
5. Split Classes That Do Two Jobs
"Too big" is a judgment call. But when a class clearly contains two ideas that could stand on their own, separate them. (The opposite extreme, a swarm of one-method classes, is just as hard to work with.)
Here is a class that does two jobs:
public class Playlist { // two concepts in one class
private String[] titles;
private int[] seconds;
public Playlist() { . . . }
public void shuffle() { . . . }
public void skip() { . . . }
public String getCurrentTitle() { . . . }
public int getCurrentSeconds() { . . . }
}
It models both a playlist (ordering, shuffling, moving on) and a track (title and length). Worse, the two parallel arrays must be kept in step by hand: shuffle one and forget the other, and every title gets the wrong length. Pull the track out into its own type. A track is plain data, so a record fits, and a fixed set of genres is better expressed as an enum than as strings or numbers. (Enums get their own article in the next part; for now, enum Genre { ... } declares a type with exactly the listed values.)

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Solution {
public static void main(String[] args) {
var list = new Playlist(new Random(7));
list.add(new Track("Blue Hour", 214, Genre.JAZZ));
list.add(new Track("Night Drive", 187, Genre.ROCK));
list.add(new Track("Harbour Song", 242, Genre.FOLK));
list.add(new Track("Neon", 165, Genre.POP));
list.add(new Track("Slow Tide", 301, Genre.JAZZ));
System.out.println("total " + list.totalSeconds() + " s");
list.shuffle();
for (int i = 0; i < 3; i++) {
System.out.println(list.next());
}
var home = new Address("14 Quay Lane", "Galway", "H91 X2Y3", "IE");
var c = new Customer("Aoife", home);
System.out.println(c.address().city());
}
}
enum Genre { JAZZ, ROCK, FOLK, POP }
record Track(String title, int seconds, Genre genre) {
Track {
if (seconds <= 0) throw new IllegalArgumentException("Bad length: " + seconds);
}
@Override
public String toString() {
return String.format("%s (%d:%02d, %s)", title, seconds / 60, seconds % 60, genre);
}
}
class Playlist {
private final List<Track> tracks = new ArrayList<>();
private final Random generator;
private int position;
public Playlist(Random generator) {
this.generator = generator;
}
public void add(Track t) { tracks.add(t); }
public void shuffle() { Collections.shuffle(tracks, generator); position = 0; }
public Track next() { return tracks.get(position++ % tracks.size()); }
public int totalSeconds() {
int sum = 0;
for (Track t : tracks) sum += t.seconds();
return sum;
}
}
record Address(String street, String city, String postalCode, String countryCode) { }
record Customer(String name, Address address) { }
total 1109 s
Slow Tide (5:01, JAZZ)
Neon (2:45, POP)
Blue Hour (3:34, JAZZ)
Galway
(The Random is seeded with 7 so the shuffle is the same on every run. A real player would use new Random().)
Professionals call this hint the Single Responsibility Principle, the "S" in the SOLID design principles: a class should have one reason to change.
6. Choose Names That State the Responsibility
A class name is a promise about what the class does, so it deserves the same care as a variable name. Even the JDK slips here: java.util.Date actually represents an instant on the timeline, with a time of day, which is one reason java.time.LocalDate was added later.
Good conventions:
- A class name is a noun (
Order), possibly with an adjective (RushOrder) or a gerund, an "-ing" word (BillingAddress). - Accessor methods start with a lowercase
get(getSalary), orisforboolean(isActive). Mutators start withset(setSalary). Records use the bare component name (salary()). - Other methods are verbs or verb phrases that say what they do:
giveRaise,shuffle,calculateTax. - Avoid vague names such as
Manager,Processor,Data,HelperorUtil, unless the class really is a grab bag. A good name makes a class's responsibility obvious and exposes a class that does too much.
7. Make Classes Immutable Where You Can
Nothing in java.time ever modifies an existing object. LocalDate.plusDays and its relatives build and return a new object, leaving the original untouched.
Mutable state becomes dangerous once several threads touch the same object: interleaved updates give results that depend on timing. An immutable object has no updates to interleave, so any number of threads can share it without locks. They're also easier to reason about (no one can change them behind your back), safe as HashMap keys and HashSet elements, and need no defensive copies.
So make classes immutable when you can. It's particularly easy for classes that represent values, such as a string, a point in time, money or a coordinate. Computations simply return new values instead of updating existing ones. Records make this nearly effortless.
How to make a class immutable:
- make all fields
private final, - provide no mutators; "changing" methods return new objects (
withSalary(...),plus(...)), - make defensive copies of mutable inputs and outputs (or use immutable types like
List.copyOf), and - prevent subclasses from adding mutable behavior: declare the class
final(records are final automatically).
Not every class should be immutable, of course. It would be strange for giveRaise to return a new Employee when an employee gets a raise. Entities with an identity that changes over time (employees, bank accounts, shopping carts) are usually mutable. Values are usually immutable.
The End of Part 4
You can now define classes, construct objects, control access and organize code into packages. Two pillars of object-oriented programming are still missing: inheritance, where one class builds on another, and polymorphism, where one call can run different code depending on the object's actual class. Part 5 starts with both, beginning with superclasses, subclasses and method overriding.
Common questions
Isn't "always keep data private" too strict for simple data? For plain data with no rules to protect, use a record. Its fields are private and final, but its accessors make the data publicly readable. You get the convenience of public data without giving up the ability to add validation or extra methods later.
How small should a class be? There is no line count. Ask whether you can describe the class's purpose in one sentence without "and". If changes for unrelated reasons (formatting, storage, business rules) keep landing in the same class, split it.
Are getters and setters "evil"? No, but setting up a getter and a setter for every field by reflex turns a class into a passive data bag with no protection. Provide operations that keep the object valid, and read access only where callers need it. Frameworks that require setters (some ORMs, for example) are a separate, pragmatic case.
When should a class be final?
When you haven't designed it for extension, especially value classes and classes with security-sensitive behaviour. You can always remove final later without breaking anyone, but adding it later breaks every subclass. Records and enums are final automatically.
What is "primitive obsession", and how much should I care?
It means using raw String, int or double values for concepts that have rules, such as email addresses, money amounts or IDs. Small value types (often records with a compact constructor) put the validation in one place and stop you from mixing up arguments of the same primitive type. Introduce them where mix-ups or repeated validation actually happen.
Summary
- Keep data private.
- Initialize all fields explicitly; prefer
final. - Replace clusters of basic-type fields with their own classes (
Address,Money). - Provide accessors and mutators only where needed; prefer meaningful operations.
- Split classes with several responsibilities (Single Responsibility Principle).
- Choose names that describe responsibilities: nouns for classes, verbs for methods,
get/set/isfor accessors and mutators. - Prefer immutable classes for values; records make it easy.
Practice Questions
A class Order has fields double amount and String currency, and every method uses them together. What hint applies, and what would you do?
Hint 3, too many basic types. Introduce record Money(BigDecimal amount, Currency currency) and give Order a Money total field. Use BigDecimal for money, as covered in the big numbers article.
Which fields of Employee (name, salary, startDate, id) should get setters?
Probably only salary, and better as a meaningful operation like giveRaise. The name might change in real life, but via an explicit operation with rules. startDate and id should never change after construction, so make them final with no setters.
Class ReportManager loads data from a database, computes statistics, formats HTML and sends emails. What's wrong, and how would you fix it?
It has four responsibilities (four reasons to change). Split it into, e.g., SalesRepository (loading), SalesStatistics (computing), HtmlReportFormatter (formatting) and ReportMailer (sending), with a small class coordinating them.
Why are immutable objects safe to share between threads?
Their state can't change after construction, so there are no concurrent updates, no inconsistent intermediate states, and no need for locks. Every thread sees the same values.
Should a BankAccount be immutable? Should a Money value be?
BankAccount models an entity whose balance changes over time, so it's naturally mutable (with careful encapsulation and thread safety). Money is a value: amount.plus(other) should return a new Money, so it should be immutable, ideally a record.
Previous: Javadoc: Writing Documentation Comments in Java
Next: Java Inheritance: Superclasses, Subclasses and Method Overriding
Related reading
- Java Package Access and the Class Path
- Java Records: Compact Data Classes with Canonical and Compact Constructors
- Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
- Defining Your Own Classes in Java: Fields, Constructors and Methods
- Using Predefined Classes in Java: Objects, Object Variables and LocalDate

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.