Clean Classes and SOLID Principles in Java
This method accepts any List, so by the type system it accepts the result of List.of() as well. The compiler is happy, and the program is not:
static void addDefaultRole(List<String> roles) {
roles.add("USER");
}
List<String> editable = new ArrayList<>(List.of("ADMIN"));
addDefaultRole(editable);
System.out.println(editable);
List<String> fixed = List.of("ADMIN");
addDefaultRole(fixed); [ADMIN, USER]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) An immutable list is a List that cannot do everything a List promises. That is a textbook case of the Liskov substitution principle — one of the five SOLID principles — and the JDK documents it by calling add() an «optional operation».
SOLID principles are five design guidelines for object-oriented classes: Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion. Together with basic class hygiene — a predictable structure, encapsulated fields, high cohesion — they keep classes small, focused and easy to change without breaking the code that uses them.
Class structure: what goes where
A clean Java class follows the same order every time, so a reader knows where to look: constants first, then static and instance fields, then constructors, then methods. Within the methods, a public method is followed by the private helpers it calls.
public class Account {
public static final BigDecimal OVERDRAFT_LIMIT = new BigDecimal("500"); // public constants
private static final Logger LOG = Logger.getLogger(Account.class.getName()); // private static fields
private final String number; // instance fields
private BigDecimal balance = BigDecimal.ZERO;
public Account(String number) { // constructors
this.number = Objects.requireNonNull(number, "number");
}
public void withdraw(BigDecimal amount) { // public methods...
checkAvailable(amount);
balance = balance.subtract(amount);
LOG.fine(() -> "Withdrawn " + amount + " from " + number);
}
private void checkAvailable(BigDecimal amount) { // ...and their helpers
if (balance.add(OVERDRAFT_LIMIT).compareTo(amount) < 0) {
throw new IllegalStateException("Insufficient funds on " + number + " for " + amount);
}
}
public BigDecimal balance() {
return balance;
}
} Every class belongs in a named package that describes a feature or a layer (com.examclouds.billing), never in the default package.
Encapsulation and the Law of Demeter
Encapsulation means that a class keeps its data private and exposes behavior instead. Fields are private, helper methods used only inside the class are private, and getters and setters are added only when a caller really needs them — not automatically for every field.
A setter for every field turns a class into a bag of data that any code can put into an invalid state. In the Account above there is no setBalance(): the balance changes only through withdraw(), which checks the rule. For classes that really are just data, a record gives you private final fields, accessors, equals and hashCode in one line, and Lombok is no longer needed for that case.
The Law of Demeter extends encapsulation to callers: a method should talk only to its own fields, its parameters and objects it creates, not to the internals of objects returned by them. A chain of getters that digs through several objects is called a train wreck:
String zip = customer.getAddress().getCity().getZip(); // knows the whole object graph
String zip = customer.shippingZip(); // asks the object for what it needs The first line breaks if any class in the chain changes its structure. Fluent APIs such as stream().filter(...).map(...) or a builder are not train wrecks: each call returns an object of the same abstraction designed for chaining, not the internals of another object.
Small classes with high cohesion
A class is cohesive when its methods work with its fields: the more fields each method uses, the more the class is one unit. Low cohesion — a group of methods that uses one half of the fields and another group that uses the other half — means that two classes are hiding inside one.
Perfect cohesion, where every method uses every field, is neither realistic nor a goal. Aim for high cohesion and many small classes rather than a few large ones. A useful test is to describe the class in one sentence without the words «and», «or» and «also»; a class called UserManager or Utils usually fails it.
When a method should be static
Make a method static when it does not use instance state and should never be polymorphic: pure functions such as Math.max(), factory methods such as List.of(), small helpers inside a class. In all other cases prefer instance methods.
Static methods cannot be overridden and are hard to replace in a test. A static call to EmailSender.send() from business logic means that every test of that logic sends email, or needs a mocking library to intercept static calls. An instance field of an interface type, injected through the constructor, avoids the problem — this is the dependency inversion principle described below. Static methods and their limits are covered in Static Methods in Java.
SOLID at a glance
SOLID is an acronym collected by Robert C. Martin for five principles that make object-oriented code easier to extend and maintain. Each principle answers a different question about a class and its dependencies.
| Principle | In one sentence | Typical violation |
|---|---|---|
| Single responsibility | A class has one reason to change | Invoice that calculates totals, renders PDF and sends email |
| Open-closed | Add behavior by adding code, not by editing working code | A switch on type repeated in several methods |
| Liskov substitution | A subtype can be used wherever its base type is expected | A subclass that throws UnsupportedOperationException from an inherited method |
| Interface segregation | Clients do not depend on methods they do not use | A fat interface whose implementations leave half the methods empty |
| Dependency inversion | High-level and low-level code both depend on abstractions | new MySqlOrderRepository() inside a service |
Single responsibility principle
The single responsibility principle says that a class should have only one reason to change — one actor or concern whose requirements drive its changes. It does not mean «one method»; it means that unrelated changes should not meet in the same file.
// Three reasons to change: pricing rules, PDF layout, mail server
class Invoice {
BigDecimal total() { /* ... */ }
byte[] toPdf() { /* ... */ }
void sendByEmail(String address) { /* ... */ }
}
// One reason each
record Invoice(List<InvoiceLine> lines) {
BigDecimal total() { /* ... */ }
}
class InvoicePdfRenderer { byte[] render(Invoice invoice) { /* ... */ } }
class InvoiceMailer { void send(Invoice invoice, String address) { /* ... */ } } When the accounting department changes a tax rule, only Invoice changes; when the designer moves the logo, only the renderer does. Each class is also easier to test: the total can be checked without generating a PDF.
Open-closed principle
The open-closed principle says that classes and modules should be open for extension but closed for modification: adding a new variant of behavior should mean adding a new class, not editing a switch in several existing ones. The classic tool for this is polymorphism.
interface Shape {
double area();
}
record Circle(double radius) implements Shape {
public double area() { return Math.PI * radius * radius; }
}
record Rectangle(double width, double height) implements Shape {
public double area() { return width * height; }
}
// Adding Triangle does not touch this method
static double totalArea(List<Shape> shapes) {
return shapes.stream().mapToDouble(Shape::area).sum();
} Modern Java offers a second option: a sealed interface with records and a pattern-matching switch. The compiler then checks that every case is handled, so adding a type breaks the build in every place that must be updated. Use polymorphism when the set of types grows and the behavior belongs to each type; use a sealed hierarchy with switch when the set of types is closed and the operations are many and change more often than the types. The trade-off is discussed in Pattern matching or polymorphism?
Liskov substitution principle
The Liskov substitution principle says that code working with a base type must keep working, without knowing it, when it receives any subtype. A subtype may do more than its parent, but it must not require more from callers or promise less to them.
The immutable list from the start of this lesson promises less than List: add() throws. The JDK accepted this compromise to avoid a separate ImmutableList type, and you have to live with it — copy into an ArrayList before modifying a list you did not create. In your own hierarchies, avoid it: if a subclass has to throw UnsupportedOperationException or ignore an inherited method, the inheritance is wrong. Typical signs are a Square extends Rectangle whose setWidth() also changes the height, or a ReadOnlyRepository that inherits save().
Interface segregation principle
The interface segregation principle says that no client should be forced to depend on methods it does not use. Large interfaces should be split into smaller, role-specific ones, so that each implementation and each caller sees only what it needs.
// A black-and-white printer must "implement" color printing
interface Printable {
void printBlackAndWhite(Document document);
void printInColor(Document document);
}
// Split by role
interface BlackAndWhitePrinter {
void printBlackAndWhite(Document document);
}
interface ColorPrinter {
void printInColor(Document document);
}
class LaserPrinter implements BlackAndWhitePrinter { /* ... */ }
class InkjetPrinter implements BlackAndWhitePrinter, ColorPrinter { /* ... */ } With the fat interface, LaserPrinter would have to throw from printInColor() — an LSP violation caused by an ISP violation. The two principles often appear together.
Dependency inversion principle
The dependency inversion principle says that high-level code should not depend on low-level details; both should depend on abstractions. In Java this usually means: a class receives its collaborators as interfaces through the constructor instead of creating concrete classes with new.
// PC is welded to one keyboard and one monitor
public class PC {
private final StandardKeyboard keyboard = new StandardKeyboard();
private final Monitor monitor = new Monitor();
}
// PC depends on abstractions; any keyboard can be plugged in
public interface Keyboard {
String readLine();
}
public class PC {
private final Keyboard keyboard;
private final Monitor monitor;
public PC(Keyboard keyboard, Monitor monitor) {
this.keyboard = keyboard;
this.monitor = monitor;
}
} Now a test can pass a fake keyboard that returns prepared input, and production code can pass a wireless one, without changing PC. Passing dependencies through the constructor is called dependency injection; it is the usual way to apply the principle, and frameworks such as Spring automate it. The same idea in miniature is programming to an interface: declare List<Employee> employees = new ArrayList<>() rather than ArrayList<Employee>, so the rest of the code does not depend on the concrete class.
Frequently Asked Questions
What is the difference between dependency inversion and dependency injection?
Dependency inversion is a design principle: high-level and low-level code both depend on abstractions. Dependency injection is a technique for applying it: a class receives its dependencies from outside, usually through the constructor, instead of creating them. Spring is a framework that performs the injection for you.
Does the single responsibility principle mean a class should have one method?
No. A class can have many methods as long as they change for the same reason. An Invoice with total(), tax() and discount() is fine; an Invoice that also renders PDF and sends email has three reasons to change. More in Single responsibility principle.
Should every class have an interface?
No. Introduce an interface where you need a second implementation, a test double or a boundary between modules, such as a repository, a payment gateway or a clock. An interface with a single implementation named FooImpl that nobody substitutes only adds a file to navigate.
Are SOLID principles still relevant with records and functional style?
Yes, although some look different. Records make single-responsibility data classes cheap, sealed hierarchies with pattern matching are an alternative to polymorphism for open-closed design, and passing a function such as Supplier or Clock is a lightweight form of dependency inversion.
Practice
Reinforce this lesson with hands-on tasks, each with a level and a time estimate.
- Replace StringBuilder Plumbing with a Small HtmlTag Class
- Replace Repeated switch Statements with an Enum
- Apply Dependency Inversion to an Order Service
Comments