Java / Spring Boot Standard

The rules for FT backend engineers (Java 21+/Spring Boot), on one page.

This page is the readable form of the ft-java-standards skill. If they differ, the skill wins. Report the difference.

The Angular team has its own standard. Both teams share one document: the Internal API Contract between the frontend (FE) and the backend (BE).

Rules at a glance

Rule In one line Section

J1 Packages

New type goes into a role sub-package (handler, service, repository…), never the root

J1

J2 Naming

Role suffix; enums end …​Enum; no I-prefix, no FT-prefix, no Hungarian

J2

J3 Immutability

Data transfer objects (DTOs) are record`s (or `@Value+@Builder); @Data never; entities only @Getter/@Setter

J3

J4 Injection

Constructor injection only

J4

J5 Logs

key=value with serial (a string), deviceId (a number) and sessionId (when a session or transaction exists); no Mapped Diagnostic Context (MDC); right level

J5

J6 Building blocks

Sealed OperationResult / AsyncResult outcomes; Optional; java.time

J6

J7 Tests

should_X_when_Y; *IT on real infra; new code ≥ 80% diff coverage (defined in J7)

J7

J8 Internal API (UI↔BE)

The wire between the Angular UI and its backend: POST-RPC, envelopes, error codes, identity

J8

J9 Protocol spec

Validate paths against the spec before coding

J9

J10 Caching

Hazelcast IMap with time to live (TTL) and eviction; no @Cacheable

J10

J11 Constants

No magic values; enums; tunables in @ConfigurationProperties

J11

J12 Libraries

JDK and Spring first; new dependency approved, pinned, scanned

J12

J-DB Database

MySQL and Oracle portable; no foreign key (FK); audit columns; atomic upsert; named indexes; batching

J-DB

J13 HTTP APIs

Two surfaces, never mixed; OpenAPI; @Valid; one @RestControllerAdvice

J13

J14 Observability

Micrometer; low-cardinality tags only

J14

J15 API security

Spring Security + JSON Web Token (JWT) on external APIs; stateless

J15

J16 Discipline

Method ≤ 40 lines, class ≤ 250, ≤ 4 parameters, nesting ≤ 3; keep it simple (KISS)

J16

J17 Exceptions

Outcomes over exceptions; never swallow; rethrow with cause

J17

J18 Idioms

Streams, Optional as return type only, injected Clock

J18

J19 Concurrency

Timeouts on every remote call; no blocking .get(); idempotent jobs

J19

J20 Security

Parameterized SQL, XML external entity (XXE) processing off, no untrusted deserialization (blocking findings)

J20

Use the review checklist at the end of the page in every pull request.

J1 · Packages = the catalog of the code

The package tree is how you find code: walk feature → role. Where a new file goes is a design decision.

The rule: a new type goes into the sub-package that matches its role (handler, service, repository, mapper, entity, config…). If that sub-package doesn’t exist, create it. Never drop a new class into the module or app root package. The root is not a junk drawer.

A feature package, catalogued by role
Figure 1. A feature package, catalogued by role
Do: feature first, role second Don’t: dumped in the root
com.friendly.device.write
  .handler.WriteTaskHandler
  .service.DeviceWriteService
  .repository.DeviceRepository
  .mapper.RegistrationMapper
com.friendly.device
  .WriteTaskHandler     <-- role lost
  .DeviceWriteService   <-- root = junk drawer
  .DeviceRepository
New role in a feature? Add the sub-package. New feature? Add the feature package, then its role sub-packages. The tree should read like a table of contents.

J2 · Naming: role suffix, no Hungarian

Rule Java

Role suffix

*Service, *Handler, *Repository, *Mapper, *Entity…

Enums

end with …​Enum

Interfaces

no I-prefix (idiomatic Java)

Variables/fields

camelCase; booleans read as predicates (enabled, hasPending)

Methods

verb phrases (findBySerial, applyWrite); is/has/can for predicates; get* only for accessors (records expose accessors without a prefix: written(), not getWritten())

Constants

UPPER_SNAKE_CASE

Forbidden

FT-prefix on classes · Hungarian notation

"Hungarian notation" = baking a variable’s type or scope into its name via a prefix, instead of letting the type system carry that. Name by meaning, not type:

  • Don’t: strName, iCount, bEnabled, lpszText, m_serial, s_instance

  • Do: name, count, enabled, text, serial, instance

The role suffixes (…​Enum, …​Properties, …​Service) are a deliberate FT convention for greppability and uniform cataloguing. They are not idiomatic Java. Where idiom and convention differ (for example enums), the convention wins on these pages.
Naming suffix vocabulary

Handler · *Service · *Store (non-JPA → Optional) · *Repository (JPA) · *Dao/*DaoJdbcImpl · *Mapper · *Resolver · *Validator · *Request/*Response (records) · *Result · *Command · *Entity (JPA) · *Properties · *Listener · *Dispatcher · Abstract · *Impl (only with an explicit interface split).

J3 · Immutability by default

Do: record DTO Don’t: mutable DTO
public record WriteResult(int written, Instant at) {}
@Data class WriteResult { ... }   // @Data anywhere is forbidden

DTOs are record`s. A large DTO that needs a builder is an immutable Lombok `@Value + @Builder, because records have no builder.

On JPA entities use only @Getter and @Setter, because entities need hydration. Never use @Data, @EqualsAndHashCode or @ToString on an entity. The generated equals, hashCode and toString use all fields and break on lazy associations, generated ids and bidirectional cycles.

@Data is never used on a DTO, because it makes the DTO mutable.

J4 · Constructor injection only

Do Don’t
@Service
@RequiredArgsConstructor
class DeviceWriteService {
  private final Sender sender;
}
@Service
class DeviceWriteService {
  @Autowired
  private Sender sender; // field injection
}

J5 · Structured, greppable logs: one file, grep by module and device (no MDC)

All logs can go to one log file if you can grep the file by module, by device and by session. Each log line carries explicit key=value fields for this. FT does not use MDC.

Why not MDC? It is thread-bound and FT flows are not.

MDC stores context in a thread-local variable. FT requests move across thread pools, Hazelcast queues, MQTT listeners and CoAP/CWMP sessions. The thread that finishes the work is rarely the thread that started it, so the MDC context disappears in the middle of the flow. Explicit ids on the session or command object survive every hop.

log-flow
Do: explicit key=value Don’t
log.info("write applied serial={} deviceId={} sessionId={} param={}",
         serial, deviceId, sessionId, path);
MDC.put("cpeSerial", serial);                 // lost across queues/sessions
log.info("write applied for cpe " + serial);  // not greppable
Field Meaning

serial

the serial number of the customer premises equipment (CPE, the device) as a string; the primary grep key; on every device-scoped line

deviceId

the numeric device id (number, not the serial); on every device-scoped line where the id is known

sessionId

when a session or transaction exists

module

the logger name (@Slf4j, one per class); pattern has %logger{36}

Use parameterized logging of the Simple Logging Facade for Java (SLF4J), or the SLF4J 2.x fluent addKeyValue for JSON sinks. A small helper can render the serial=… deviceId=… sessionId=… prefix consistently.
Table 1. Levels & frequency
Level When

ERROR

an operation failed and needs attention (context + cause). Log once, at the owning boundary: not log-and-rethrow at every layer. Not for handled/expected outcomes.

WARN

recoverable / degraded: retry, fallback, deprecated path, slow response.

INFO

significant, low-cardinality business events (device registered, task completed). never per-message / per-loop.

DEBUG

developer detail (payloads, decisions); off in prod by default.

TRACE

very fine, per-iteration.

On a firehose (MQTT/CoAP/telemetry) never log at INFO per message: use DEBUG/TRACE, aggregate (processed N in T ms), or throttle/sample. Guard with log.isDebugEnabled() only when building the argument is itself expensive (parameterized logging already defers toString).

J6 · Outcomes & building blocks

Outcomes, not exceptions. Handlers return sealed OperationResult / AsyncResult and pattern-match:

return switch (asyncResult) {
  case AsyncResult.Success<T>(var v) -> new OperationResult.Success<>(map(v));
  case AsyncResult.Error<T>(var e)   -> toDeviceError(e);
  case AsyncResult.Timeout<T> ignored -> toTimeout();
};

Use @Slf4j for logging, @UtilityClass for static-only utilities, Optional<T> instead of null, and java.time.* for time.

J7 · Tests and test-driven development (TDD)

Convention Rule

Method name

should_<expected>_when_<condition> + @DisplayName + @Nested

*Test

unit test: mock collaborators

*IT

integration test on real infrastructure (Testcontainers, in-memory database or protocol emulator). Never mock the DB

Coverage

New or changed code ≥ 80% line and branch diff coverage. Diff coverage is the share of added or changed lines and branches that tests run. Measure it with JaCoCo and diff-cover. There is no global gate, so legacy code is not blocked.

Test quality

Never mock the subject under test; mock boundaries only (repository, remote client, time). Tests are deterministic: inject Clock, no Thread.sleep, no real network in *Test. One behaviour per test

Assertions

new test classes use AssertJ (assertThat); inside an existing class match its style

Cover behaviour and edge cases, not lines. A line that runs without an assertion does not count. Do not write tests only to raise the number.
Choose the workflow for the task
  • Architecture-led (new module or feature, refactor, cross-cutting change): an approved design brief before any implementation. ft-developer drafts the brief from the template (the file is SDD.md) and the person running the session approves it. Then coding starts. See Glossary: design brief, SDD.

  • TDD-led (bug fix, business rule, protocol message with a known spec): write the failing test first. No design brief is needed.

@Test @DisplayName("writes a single resource value")
void should_write_value_when_path_is_writable() { ... }

J8 · Internal API (UI↔BE)

The Internal API Contract owns this rule. The Angular standard states it identically (C8). The northbound REST surface is J13 and the External API Contract.

J9 · Protocol spec = source of truth

For any protocol parameter or message work, validate paths and semantics against the authoritative spec before you write code or tests. The specs are BBF TR-069, TR-181 and TR-369, and OMA LwM2M. Derive fixtures from the worked examples in the spec.

Use the data-model XML of your repository (the skill does not name a path), the bbf_params and bbf_protocol_specs collections of the Knowledge Base, and the cwmp-xml and oma-lwm2m-expert skills.

J10 · Caching

Do Don’t
IMap<String, DeviceView> cache =
    hazelcast.getMap("deviceBySerial");
cache.put(serial, view);
@Cacheable("x")                  // Hazelcast is NOT a Spring
DeviceView load(String s) {...}  // CacheManager here

private static final Map<String,X> CACHE = ...;
Configure every IMap with TTL + max-size + eviction. Cache reads, evict on the write path. Don’t cache the per-CPE telemetry firehose (ClickHouse). A cache is never a source of truth.

J11 · Constants & enums

Do Don’t
private static final int MAX_BATCH = 1000;
enum TaskStateEnum { PENDING, DONE, FAILED }
if (state == 2) ...           // magic number
if ("DONE".equals(s)) ...     // magic string
int timeoutMs = 5000;         // belongs in properties

Shared keys: error codes, header names, protocol paths: are named constants in one place.

J12 · External libraries

  • Prefer the JDK and Spring first, then a library already in the repository. Do not add a second library for a job that an existing one does (no two JSON, HTTP or date libraries).

  • A new dependency needs approval from the person running the session. Pin versions (no +, latest or ranges). Manage versions centrally (BOM or version catalog).

  • A vulnerability scan is part of "done" when dependencies change. Upgrade when it is safe. For each HIGH or CRITICAL finding that you cannot upgrade, open a Jira task with the CVE and a deadline, and link it from the PR. Never use --force and never silence the scanner. Respect licenses: no GPL or AGPL library ships without sign-off.

J-DB · Database contract

J-DB sits between J12 and J13 and has no number.

Customers pick MySQL OR Oracle. No foreign keys. Deliberate indexes. ClickHouse only for QoE. Batch the hot tables.

Naming (tables & columns)

snake_case, singular table names (cpe, cpe_async_task); no reserved words. FK columns end id (a plain app-enforced id); booleans is/has_; timestamps at/_date; indexes <table><cols>_idx. Keep identifiers portable and short. Oracle allows 128 characters since 12.2, but legacy schemas allow 30.

Audit columns (every business table)

created / creator and updated / updator. created and updated are timestamps (insert and every update). creator and updator record the actor. Populate via Spring Data JPA auditing (@CreatedDate/@CreatedBy/@LastModifiedDate/@LastModifiedBy + AuditingEntityListener) or in the JDBC upsert. Append-only ClickHouse time series are exempt, because created is the partition and sort key.

Create-or-update = atomic upsert (not read-then-write)

Do: one atomic statement Don’t: SELECT then branch
-- MySQL
INSERT INTO cpe_parameter (...) VALUES (...)
ON DUPLICATE KEY UPDATE value = ?, status = ?;
-- Oracle (paired, chosen by dbms)
MERGE INTO cpe_parameter a USING (...) incoming
  ON (a.id = incoming.id)
WHEN MATCHED THEN UPDATE SET a.value = ...
WHEN NOT MATCHED THEN INSERT (...) VALUES (...);
var row = repo.findByKey(k);       // TOCTOU race under
if (row == null) repo.insert(...); // concurrency +
else             repo.update(...); // extra round-trip
Keep the …MySQL and …Oracle SQL pair. Examples: CpeParameterAutomationDaoJdbcImpl and CpeEventAutomationDaoJdbcImpl in the ftacs repository, module FT_CpeManagement/ftdm-events. The upsert needs a unique key or constraint to match on.

Portable MySQL/Oracle (Liquibase)

<property name="number" value="int(11) unsigned" dbms="mysql"/>
<property name="number" value="number(11)"       dbms="oracle"/>
<property name="now"    value="now()"   dbms="mysql"/>
<property name="now"    value="sysdate" dbms="oracle"/>

<changeSet id="seq" author="x" dbms="oracle">
  <createSequence sequenceName="CPE_PARAMETER_0"/>
</changeSet>
Concept MySQL Oracle

boolean

tinyint(1)

number(1)

text

longtext

clob

auto id

AUTO_INCREMENT

sequence TABLE_0

paging

LIMIT

OFFSET/FETCH (12c+); ROWNUM legacy

No foreign keys · deliberate indexes

Do Don’t
-- relation = plain id, app-enforced
cpe_id  INT
-- named, justified, guarded index
-- idx: lookup by serial+protocol
CREATE INDEX cpe_serial_protocol_idx ...
ALTER TABLE ... ADD FOREIGN KEY (cpe_id) ...
CREATE INDEX idx1 ON cpe(col);  -- unnamed/unjustified
No DB-level FK means referential integrity is app-enforced: guard inserts, clean up orphans in code/jobs, and never let a missing parent corrupt a flow. The trade is portability, not "don’t care".

ClickHouse = quality of experience (QoE) and periodic data only

CREATE TABLE cpe_data (serial String, name_id UInt32, value String, created DateTime)
ENGINE = MergeTree
PARTITION BY toDate(created)
ORDER BY (serial, name_id, created)
SETTINGS index_granularity = 8192;
-- current-state: ReplacingMergeTree(version) + is_deleted

Batch the overloaded tables

jdbc.batchUpdate(sql, rows, BATCH_SIZE, (ps, row) -> { ... });
// relational ~1000 (+ order_inserts, rewriteBatchedStatements)
// ClickHouse ~100 · drain queues with drainTo + bulk, re-queue on failure
Default persistence = Spring Data JPA (relational); raw JdbcTemplate for ClickHouse & hot paths. Don’t grow new hand-rolled *DaoJdbcImpl.

Transactions · N+1 · pagination

  • Put @Transactional on the service layer, not on controllers or repositories. Use readOnly = true on query paths. Self-invocation is not proxied: a @Transactional method called from the same class runs without a transaction. Split the bean. Use REQUIRES_NEW only deliberately.

  • No repository or remote call inside a loop (the N+1 problem). Batch it with an IN query, a fetch join or @EntityGraph, a projection, or a batch fetch size. Verify hot queries by count (Hibernate statistics or a query counter in an *IT), not by eyeballing.

  • Every new listing endpoint/query over a growing table is bounded: Pageable or an explicit limit. An unbounded findAll() on a growing table is a defect, not a style choice.

J13 · HTTP APIs: two styles, documented, validated

FT has two API surfaces. Use the rules of the surface you work on and never mix them. The full contracts are the Internal API Contract (UI↔BE) and the External API Contract (REST).

Internal API (UI↔BE) Northbound / public / integration

Style

POST-RPC /{controller}/{action}

REST: @RestController + @RequestMapping("api/<Resource>"), verb by semantics

Errors

The correct HTTP status plus an FT error code in the body. This is a goal, not a guarantee. Service-to-service calls follow the same rule.

HTTP 200 plus the FT code in the body. An unauthenticated call gets 401, and an unexpected failure gets 500.

Error catalog

Internal 90xx, for example 9024

Separate: StatusResponse.errorCode (100 or 20X). Never mix the two catalogs.

Versioning

Not applicable

None. The API is additive-only (api/<Resource>, no /v1). A breaking change is a new resource or endpoint.

Verbs, DTO names and the reference repositories of each surface are in the two contracts above.

  • Document every public endpoint with springdoc OpenAPI: @Tag (controller), @Operation (method), @Schema (fields). A public API without OpenAPI is incomplete.

  • Validate at the boundary: @Valid/@Validated + jakarta.validation (@NotNull/@NotBlank/@Size) on the request DTO.

  • One global @RestControllerAdvice per service maps exceptions to the error shape in the table above. No per-controller try/catch. Never leak stack traces.

J14 · Observability

  • Metrics via Micrometer + Actuator, scraped by Prometheus; custom metrics through MeterRegistry / @Timed.

  • Low-cardinality tags only. Never use a per-serial tag, because the number of distinct tag values grows without limit. The serial belongs in logs (J5).

  • Metrics are rates, latency and counts. Logs are events with serial, deviceId and sessionId.

J15 · API security (external surfaces)

  • External APIs: Spring Security SecurityFilterChain + JWT (jjwt); @PreAuthorize for method-level rules.

  • Stateless: CSRF disabled, no server session; auth/authorization failures → 401 / 403 via the global handler.

  • Never log tokens or secrets. Signing keys live in configuration or secrets, not in code.

J16 · Method and class discipline: readable code

These are review norms, not CI gates. To exceed one, state the reason in the pull request.

Threshold Rule

Method ≤ 40 lines

linear no-branch method may reach ~60 with a reason

Class ≤ 250 lines / ≤ 20 public methods

split by responsibility

≤ 4 parameters

more → a parameter object (record)

Nesting ≤ 3

flatten with guard clauses / early return: happy path unindented

  • One level of abstraction per method: don’t mix SQL/HTTP mechanics with business flow; extract the mechanics.

  • Rule of Three: DRY is about knowledge, not lines: 2 duplicates → leave + mark // DUPE:; the 3rd → extract. Look-alike blocks that change for different reasons are not duplicates. A wrong abstraction costs more than duplication.

  • YAGNI applies to capabilities, never to quality: no "future-proof" params or config knobs without a consumer; but never an excuse to skip tests/error handling/cleanup.

  • No speculative interface+impl: a single-implementation @Service gets no interface (Mockito mocks classes fine); add it when the second implementation arrives. *Impl only with a real split (J2 suffix vocabulary).

  • Composition over inheritance; closed hierarchies = sealed + records (J6).

  • Comments say WHY (constraint, protocol quirk, trade-off): never narrate what the next line does. No tutorial comments, no commented-out code in commits.

Simplicity first (KISS)

Solve it the simplest way that passes the tests and reveals intent:

  • Lambdas and method references over anonymous classes: items.forEach(this::process), Comparator.comparing(Device::serial); no new Comparator<>() { … } boilerplate. A lambda ≤ ~3 lines; longer → extract a named private method and reference it.

  • The smallest construct that works: a method beats a class; a class beats a hierarchy; a hierarchy beats a framework. No patterns for their own sake: no factory/strategy/builder/ wrapper where a constructor or direct call does the job; a pattern earns its complexity with a real, present need (Rule of Three, not a hunch).

  • No cleverness: nested ternaries, one-liners that need a comment to decode, reflection or generics gymnastics where plain code works. If the reviewer has to pause: too clever.

  • No premature optimization: write the clear version first; complicate only with a measurement in hand (J19 / perf).

J17 · Exceptions & error flow

  • Handlers return outcomes, not exceptions: sealed OperationResult/AsyncResult (J6); exceptions are for boundary precondition violations and truly exceptional states.

  • Never swallow: no empty catch, no blanket catch (Exception e) over a method body: catch the narrowest type you can actually handle; the rest propagates.

  • Rethrow with cause: never drop the original exception; never log and rethrow (one owner per failure: J5).

  • Fail fast at the boundary (@Valid, Objects.requireNonNull(x, "msg")) so deep code assumes sane state.

  • No exceptions for control flow: expected outcomes (not-found on a lookup) belong in the result type / Optional.

J18 · Modern Java idioms

  • Streams for collection transformations (map/filter/collect): don’t default to imperative loops out of habit; imperative for is right for side-effect loops and complex early termination. No side effects in map/filter.

  • Optional is a return type only. Never use it as a field, a parameter or a collection element. Never call .get(). Use orElse, orElseThrow, map or ifPresent.

  • var when the type is obvious from the right-hand side; never in signatures. Text blocks for multi-line SQL/JSON/XML.

  • Time is java.time.* only. Never use java.util.Date or Calendar. Logic that reads "now" takes an injected Clock (J7 testability).

  • Closed sets = sealed interface + pattern-matching switch: exhaustive, no default that hides a missed case (J6).

J19 · Concurrency & async

  • Every remote call has explicit timeouts (connect + read): no library-default infinities; a hot-path sync call also needs a deliberate failure strategy (retry with backoff / circuit breaker / fallback).

  • Never block indefinitely on a request thread: no .get()/.join() without a timeout; compose CompletableFuture stages (thenApply/thenCompose/exceptionally).

  • Virtual threads (Java 21+ repositories): no synchronized around I/O, because it pins the carrier thread. Use ReentrantLock. Audit ThreadLocal, because context travels on objects (J5).

  • Shared state: immutability first (J3); else java.util.concurrent collections/atomics: no hand-rolled synchronized patterns.

  • @Scheduled / bulk jobs: protect against overlap (fixedDelay, or a DB lock / FOR UPDATE SKIP LOCKED with multiple instances); make jobs idempotent: they will rerun.

J20 · Security baseline (code-level)

Violations here are blocking review findings, not style notes. API-surface rules: J15.
  • SQL: parameterized only: JPA named parameters or JdbcTemplate ?. Never concatenate a value into SQL, including ORDER BY and column names from input. Whitelist those.

  • XML and SOAP parsing: XML external entity (XXE) processing off, everywhere. TR-069/CWMP is XML, so this is our attack surface. Set disallow-doctype-decl, turn external entities off and allow no external DTD on every factory (DocumentBuilderFactory, SAX, StAX, TransformerFactory, JAXB source).

  • No Java deserialization of untrusted data (ObjectInputStream.readObject): JSON/Protobuf instead; Jackson polymorphic typing only with an explicit allowlist validator.

  • Secrets never in code, config defaults, logs, URLs, or exception messages; rotatable without a code change.

  • Security-meaningful randomness (tokens, nonces) = SecureRandom: never java.util.Random/Math.random().

  • Files from user input: resolve against a base dir + normalize() + verify startsWith(base).

  • Bind requests to DTO records (J3), never to an @Entity: mass assignment.

  • OS commands: ProcessBuilder with an argument list: never a shell string with input concatenated in.

Review checklist

  • New type in a role sub-package, not the root

  • DTO is a record (or immutable @Value+@Builder if large); @Data never on a DTO, @Getter/@Setter only on JPA entities

  • Constructor injection; no field @Autowired

  • Logs carry serial, deviceId and sessionId as key=value; no MDC; module = logger name; right level, no INFO on hot paths

  • Tests should_X_when_Y + @DisplayName; IT on *real infra; new code ≥ 80% diff coverage

  • No magic numbers/strings; fixed sets are enum`s; tunables in `@ConfigurationProperties

  • Caching on Hazelcast (IMap, TTL+eviction): no @Cacheable/Spring CacheManager, no hand-rolled Map

  • New dependency justified + pinned + vuln-scanned; no duplicate-purpose library

  • HTTP API: right surface (internal UI↔BE POST-RPC or northbound REST); OpenAPI; request @Valid; one global @RestControllerAdvice (errors by layer: 200 plus code external, correct HTTP status plus code internal)

  • Metrics via Micrometer/Actuator (low-cardinality tags); external APIs secured (Spring Security + JWT, @PreAuthorize)

  • Protocol paths validated against the spec first

  • DB: portable, no FK, snake_case singular names, audit cols (created/creator/updated/updator), atomic upsert (no select-then-write), named index, batch hot tables

  • DB use: @Transactional at the service layer (readOnly reads); no call-in-loop N+1; new listings paginated/bounded

  • No I-prefix, no FT-prefix, no Hungarian; camelCase vars, verb methods; enums end …​Enum

  • Size discipline: method ≤ 40 lines, ≤ 4 params (else a record), nesting ≤ 3; no speculative interface+impl; comments say why; no commented-out code

  • Simplicity: lambdas/method references; the smallest construct that works; no patterns without a present need; no clever one-liners; no premature optimization

  • Exceptions: none swallowed; narrowest catch; rethrow with cause; results-not-exceptions in handlers

  • Idioms: streams for transforms; Optional return-only, no .get(); java.time + injected Clock

  • Concurrency: remote calls have timeouts; no blocking .get()/.join() on request paths; no synchronized around I/O; @Scheduled overlap-safe + idempotent

  • Security baseline: parameterized SQL only; XXE off on every XML/SOAP parser; no untrusted Java deserialization; SecureRandom; DTO binding (never @Entity)