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 idiominstead of
records for dataLombok @Data classes, mutable POJOs
constructor injection@Autowired fields
sealed types + switchinstanceof chains and visitor boilerplate
packages by feature (transfers, ledger)packages by layer (controllers, services, repositories)
Clock injectedLocalDateTime.now() scattered (untestable)
java.time typesDate and Calendar