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 ( |
|
J2 Naming |
Role suffix; enums end |
|
J3 Immutability |
Data transfer objects (DTOs) are |
|
J4 Injection |
Constructor injection only |
|
J5 Logs |
|
|
J6 Building blocks |
Sealed |
|
J7 Tests |
|
|
J8 Internal API (UI↔BE) |
The wire between the Angular UI and its backend: POST-RPC, envelopes, error codes, identity |
|
J9 Protocol spec |
Validate paths against the spec before coding |
|
J10 Caching |
Hazelcast |
|
J11 Constants |
No magic values; enums; tunables in |
|
J12 Libraries |
JDK and Spring first; new dependency approved, pinned, scanned |
|
J-DB Database |
MySQL and Oracle portable; no foreign key (FK); audit columns; atomic upsert; named indexes; batching |
|
J13 HTTP APIs |
Two surfaces, never mixed; OpenAPI; |
|
J14 Observability |
Micrometer; low-cardinality tags only |
|
J15 API security |
Spring Security + JSON Web Token (JWT) on external APIs; stateless |
|
J16 Discipline |
Method ≤ 40 lines, class ≤ 250, ≤ 4 parameters, nesting ≤ 3; keep it simple (KISS) |
|
J17 Exceptions |
Outcomes over exceptions; never swallow; rethrow with cause |
|
J18 Idioms |
Streams, |
|
J19 Concurrency |
Timeouts on every remote call; no blocking |
|
J20 Security |
Parameterized SQL, XML external entity (XXE) processing off, no untrusted deserialization (blocking findings) |
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.
| Do: feature first, role second | Don’t: dumped in the root |
|---|---|
|
|
| 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 |
|
Enums |
end with |
Interfaces |
no |
Variables/fields |
|
Methods |
verb phrases ( |
Constants |
|
Forbidden |
|
|
"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:
|
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 |
|---|---|
|
|
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 |
|---|---|
|
|
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.
| Do: explicit key=value | Don’t |
|---|---|
|
|
| Field | Meaning |
|---|---|
|
the serial number of the customer premises equipment (CPE, the device) as a string; the primary grep key; on every device-scoped line |
|
the numeric device id (number, not the serial); on every device-scoped line where the id is known |
|
when a session or transaction exists |
module |
the logger name ( |
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.
|
| Level | When |
|---|---|
|
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. |
|
recoverable / degraded: retry, fallback, deprecated path, slow response. |
|
significant, low-cardinality business events (device registered, task completed). never per-message / per-loop. |
|
developer detail (payloads, decisions); off in prod by default. |
|
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 |
|
|
unit test: mock collaborators |
|
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 |
Test quality |
Never mock the subject under test; mock boundaries only (repository, remote client, time). Tests are deterministic: inject |
Assertions |
new test classes use AssertJ ( |
| 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 |
|---|---|
|
|
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 |
|---|---|
|
|
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
+,latestor 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
--forceand 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 |
|---|---|
|
|
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 |
|
|
text |
|
|
auto id |
|
sequence |
paging |
|
|
No foreign keys · deliberate indexes
| Do | Don’t |
|---|---|
|
|
| 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
@Transactionalon the service layer, not on controllers or repositories. UsereadOnly = trueon query paths. Self-invocation is not proxied: a@Transactionalmethod called from the same class runs without a transaction. Split the bean. UseREQUIRES_NEWonly deliberately. -
No repository or remote call inside a loop (the N+1 problem). Batch it with an
INquery, 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:
Pageableor an explicit limit. An unboundedfindAll()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 |
REST: |
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 |
Error catalog |
Internal |
Separate: |
Versioning |
Not applicable |
None. The API is additive-only ( |
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
@RestControllerAdviceper 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,deviceIdandsessionId.
J15 · API security (external surfaces)
-
External APIs: Spring Security
SecurityFilterChain+ JWT (jjwt);@PreAuthorizefor method-level rules. -
Stateless: CSRF disabled, no server session; auth/authorization failures →
401/403via 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 ( |
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
@Servicegets no interface (Mockito mocks classes fine); add it when the second implementation arrives.*Implonly 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); nonew 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 blanketcatch (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; imperativeforis right for side-effect loops and complex early termination. No side effects inmap/filter. -
Optionalis a return type only. Never use it as a field, a parameter or a collection element. Never call.get(). UseorElse,orElseThrow,maporifPresent. -
varwhen 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 usejava.util.DateorCalendar. Logic that reads "now" takes an injectedClock(J7 testability). -
Closed sets =
sealedinterface + pattern-matchingswitch: exhaustive, nodefaultthat 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; composeCompletableFuturestages (thenApply/thenCompose/exceptionally). -
Virtual threads (Java 21+ repositories): no
synchronizedaround I/O, because it pins the carrier thread. UseReentrantLock. AuditThreadLocal, because context travels on objects (J5). -
Shared state: immutability first (J3); else
java.util.concurrentcollections/atomics: no hand-rolledsynchronizedpatterns. -
@Scheduled/ bulk jobs: protect against overlap (fixedDelay, or a DB lock /FOR UPDATE SKIP LOCKEDwith 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, includingORDER BYand 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: neverjava.util.Random/Math.random(). -
Files from user input: resolve against a base dir +
normalize()+ verifystartsWith(base). -
Bind requests to DTO records (J3), never to an
@Entity: mass assignment. -
OS commands:
ProcessBuilderwith 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+@Builderif large);@Datanever on a DTO,@Getter/@Setteronly on JPA entities -
Constructor injection; no field
@Autowired -
Logs carry
serial,deviceIdandsessionIdaskey=value; no MDC; module = logger name; right level, no INFO on hot paths -
Tests
should_X_when_Y+@DisplayName;ITon *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/SpringCacheManager, no hand-rolledMap -
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:200plus 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_casesingular names, audit cols (created/creator/updated/updator), atomic upsert (no select-then-write), named index, batch hot tables -
DB use:
@Transactionalat the service layer (readOnlyreads); no call-in-loop N+1; new listings paginated/bounded -
No
I-prefix, noFT-prefix, no Hungarian;camelCasevars, 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;
Optionalreturn-only, no.get();java.time+ injectedClock -
Concurrency: remote calls have timeouts; no blocking
.get()/.join()on request paths; nosynchronizedaround I/O;@Scheduledoverlap-safe + idempotent -
Security baseline: parameterized SQL only; XXE off on every XML/SOAP parser; no untrusted Java deserialization;
SecureRandom; DTO binding (never@Entity)
| Next: the Angular standard and the shared Internal API Contract (UI↔BE). |