Part 4 · 1 chapters · ~8 min
Idioms
Effective Java in modern form: immutability by default, records over Lombok, composition over inheritance, small interfaces, dependency injection through constructors, streams used with restraint, exceptions as part of the API, try-with-resources, and package structure by feature.
7
Writing modern Java
code
// constructor injection: dependencies explicit, fields final, easy to test without a container
@Service
public class TransferService {
private final LedgerRepository ledger; private final Clock clock;
public TransferService(LedgerRepository ledger, Clock clock) { this.ledger = ledger; this.clock = clock; }
}
// try-with-resources: closed even on exceptions
try (var conn = dataSource.getConnection(); var ps = conn.prepareStatement(SQL)) { ... }
// streams with restraint: clear transformations, not puzzles
long pendingKobo = transfers.stream().filter(t -> t.state() == State.PENDING).mapToLong(Transfer::amountKobo).sum();| modern idiom | instead of |
|---|---|
| records for data | Lombok @Data classes, mutable POJOs |
| constructor injection | @Autowired fields |
| sealed types + switch | instanceof chains and visitor boilerplate |
packages by feature (transfers, ledger) | packages by layer (controllers, services, repositories) |
Clock injected | LocalDateTime.now() scattered (untestable) |
java.time types | Date and Calendar |