Java / Java 21 Coding Standards Interview Questions
How do you apply the Single Responsibility Principle in Java 21 class design standards?
The Single Responsibility Principle says a class should have exactly one reason to change; in practice this means separating "what the data is" from "what happens to it" and from "how it is delivered or persisted".
public record Invoice(String id, BigDecimal total) {} // data public class InvoiceTaxCalculator { BigDecimal apply(Invoice i) {...} } // one responsibility public class InvoiceRepository { void save(Invoice i) {...} } // another responsibility
Java 21's records make the "data" half of this split explicit and enforced by the compiler: a record cannot quietly grow business logic that depends on mutable internal state, because it has none, which naturally pushes behavior out into dedicated collaborator classes like a calculator or a validator.
A practical litmus test during review is to describe the class's job in one sentence without using "and" - if a class needs "calculates tax and saves the invoice and sends a notification" to be described accurately, it has three responsibilities and should be split into three classes.
More Related questions...