code-quality-jvm
Skill345 starsChanged 35 days agoApache-2.0View on GitHub
Use when writing or reviewing Java (or Scala) in this repo's JVM modules (sink-connector, sink-connector-lightweight), or when asked for "worldclass"/"idiomatic" Java. Covers Effective Java greatest hits (records, immutability, Optional, static factories, builders, sealed types), a deep concurrency/resource/correctness review checklist, and the google-java-format/Checkstyle/SpotBugs/ErrorProne toolchain.
In this repository17 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- clickhouse-sink-reviewSkill
- code-quality-architectureSkill
- code-quality-bashSkill
- code-quality-goSkill
- code-quality-pythonSkill
- code-quality-sqlSkill
- code-reuse-firstSkill
- code-reuse-reviewSkill
- design-note-debtSkill
- destructive-operation-safetySkill
- mandatory-code-change-validationSkill
- pr-self-reviewSkill
- repro-harness-negative-proofSkill
- sink-connector-mysql-source-of-truthSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 74
Optionovernull; never.get: Treat Option as a collection — map/flatMap/fold/getOrElse. - Very specific: line 100
Run this over every changed .java file during pr-self-review's per-language pass.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Worldclass Java / Scala (Java 17+, modern Scala)
Overview
Idiomatic JVM code for this project's Java 17 / Maven modules:
sink-connector and sink-connector-lightweight. Favor immutability,
exhaustive types, and the standard JVM quality gates. The Scala section
below applies only if a module in scope uses Scala; otherwise skip it.
When to Use
- Writing or reviewing
.java(or.scala) insink-connectororsink-connector-lightweight - Designing a JVM API, domain model, or error model for this connector
- A user asks for "worldclass / idiomatic" Java or Scala
Java — Core Rules
Why these: Effective Java's through-line is immutability + clear contracts. Modern Java (records, sealed types, pattern switch) makes them low-friction.
- Records for immutable data carriers — DTOs, events, value objects:
record Point(int x, int y) {}. Autoequals/hashCode/toString/accessors, implicitly final. Prefer over Lombok/POJOs. - Minimize mutability (EJ 17).
finalfields by default; immutable classes unless there's a compelling reason — they're thread-safe and safe as map keys. - Sealed hierarchies + records + exhaustive switch (Java 17/21):
sealed interface Shape permits Circle, Rectangle→ compiler-checked switch, nodefaultneeded. Optionalovernullfor possibly-absent return types. Never for fields or params; never call.get()blindly.- try-with-resources for any
AutoCloseable— never manualtry/finally close. - Static factories over constructors (EJ 1) — named, cacheable, can return
subtypes (
List.of,Optional.of). - Builder for many params (EJ 2) — beyond ~4 params or many optionals.
- Favor composition over inheritance (EJ 18). Design for inheritance or
prohibit it (
final). - Program to interfaces (EJ 20, 64) — refer to objects by interface type
(
MapnotHashMap). - Honor
equals/hashCodetogether (EJ 10–11) — records do this for you. - Fail fast & defensive copies (EJ 49–50) — validate params early, copy mutable inputs/outputs at boundaries.
- Streams judiciously (EJ 45) — great for transformations; don't force every loop into a stream. Readability first.
// BAD // GOOD
class Point { int x, y; record Point(int x, int y) {}
Point(int x,int y){this.x=x;this.y=y;} }
String s = map.get(k); Optional<String> s = Optional.ofNullable(map.get(k));
if (s != null) use(s); s.ifPresent(this::use);
Conn c = open(); try { use(c); } try (Conn c = open()) { use(c); }
finally { c.close(); }Java tooling: Maven (mvn -o test, offline, per AGENTS.md) ·
google-java-format · Checkstyle (style) · SpotBugs (bug patterns) ·
Error Prone (compile-time bug detection). Wire as CI gates.
Scala — Core Rules
Why these: Scala rewards referential transparency and sum types; restraint (Principle of Least Power) keeps a large language readable.
valovervar; immutable collections. Mutable state only to model genuinely mutable things.Optionovernull; never.get. TreatOptionas a collection —map/flatMap/fold/getOrElse.Either[Err, T]/Try[T]over thrown exceptions. One failure mode →Option; multiple → sealed-trait error ADT /Either.- Case classes + sealed traits = ADTs — immutable,
copy, structural equality, free extractors. - Pattern matching over if-else chains — expression-oriented, no fall-through.
- Exhaustiveness checking — seal traits and enable
-Xfatal-warningsso non-exhaustive matches are compile errors. for-comprehensions to sequenceOption/Either/Try/Futureinstead of nestedflatMap.- Implicits /
givens sparingly and explicitly — powerful but fragile.
// BAD // GOOD
var total = 0 val total = items.map(_.price).sum
for (i <- items) total += i.price
def find(k: K): V = map(k) // throws def find(k: K): Option[V] = map.get(k)
if (x != null) use(x) opt.fold(default)(use)Scala tooling: sbt · scalafmt (.scalafmt.conf, maxColumn <= 100, --check
in CI) for formatting · scalafix (DisableSyntax.noVars/noNulls/noThrows,
OrganizeImports, RemoveUnused, --check in CI) for lint/refactor.
Deep Review Checklist (Java)
Run this over every changed .java file during pr-self-review's
per-language pass. Each item is a bug class a reviewer must actively hunt
for, not a style rule.
Concurrency (Java Concurrency in Practice; SpotBugs MT_/IS_/JLM_ patterns)
- Every shared mutable field has exactly one documented guard (a lock,
volatilefor single-writer flags, anAtomic*, or confinement). Mixed guarded/unguarded access is a race.@GuardedByor a comment names it. This matters especially in the batch executor and offset-tracking paths, where a race directly risks Invariant I8 (Durable Offset Quiescence). - No check-then-act across a lock boundary —
if (!map.containsKey(k)) map.put(k, v)on aConcurrentHashMapis a race; useputIfAbsent/computeIfAbsent.volatile x++is not atomic. InterruptedExceptionis never swallowed — either rethrow or restore withThread.currentThread().interrupt()before returning. A loop that catches it and continues makes shutdown hang.- Executors and threads are shut down on every exit path (
shutdown()- bounded
awaitTermination, thenshutdownNow()); threads are named and daemon-ness is deliberate. Exceptions fromsubmit()ed tasks are lost unless theFutureis read — preferexecute()with an uncaught handler or check every future.
- bounded
- Queues and caches are bounded; an unbounded
LinkedBlockingQueuefeeding a slower consumer is a heap-exhaustion bug. Backpressure is explicit. - No blocking calls or callbacks to foreign code while holding a lock;
lock ordering is consistent (deadlock).
wait()is always in a loop on its condition. - Publication is safe — objects shared across threads are published
through
finalfields, avolatile, a concurrent collection or a lock; nothisescape from a constructor (starting a thread or registering a listener in a constructor). - Iteration over shared collections —
ConcurrentModificationExceptionwhen a collection is modified while iterated; snapshot or use a concurrent collection.
Resources and errors
9. Every AutoCloseable (Connection, Statement, ResultSet, stream,
channel) is in try-with-resources, including on error and early-return
paths. A PreparedStatement reused across batches is closed exactly once.
10. No catch of Exception/Throwable that hides unrelated failures;
never an empty catch; never log-and-continue where the caller needs to
know; never log-and-rethrow (double logging) — handle once. Wrapped
exceptions keep the cause (new X(msg, e)). A swallowed exception on
the apply path is a direct violation of Invariant I9 (Loud Failure).
11. finally does not throw or return (masks the original exception).
12. Errors carry context — what failed, on which table/offset/source,
and what the operator should do.
Correctness
13. equals and hashCode together, consistent with compareTo where
sorted collections are used; mutable fields are never part of a hash key.
14. Integer overflow and unit errors — int byte counts over 2 GiB,
long millis vs nanos vs seconds, Duration misuse; Math.toIntExact
/ addExact where overflow would corrupt state.
15. Nulls at boundaries — values from maps, JDBC (getInt returns 0 for
NULL; check wasNull()), deserialized records and config. JDBC
wasNull() handling matters directly here: the column-kind contract
(ordinary columns must bind NULL, not silently coerce to a default)
depends on getting this right.
16. String/charset/locale — getBytes() without a charset,
toLowerCase() without Locale.ROOT, String.format with default
locale for machine-readable output.
17. Time — System.currentTimeMillis() for measuring durations (use
nanoTime()), java.util.Date/SimpleDateFormat (not thread-safe),
implicit default time zone — timestamp handling is especially
sensitive here around DST transitions and source-vs-commit time.
18. Static mutable state — singletons and static caches shared across
tasks/tests; hidden coupling and test-order dependence.
Logging and performance
19. Parameterized logging (log.info("x={}", x)) — no string
concatenation or String.format in hot-path log statements; no
per-record INFO/WARN logging; no secrets or full row payloads in logs.
20. Hot-path allocation — boxing in tight loops, regex compiled per
call (String.split/replaceAll with a regex in a loop), streams in
per-record paths where a loop is clearer and cheaper.
21. JDBC — batches are bounded; statements are prepared, never built by
concatenating untrusted values (SQL injection); identifiers are quoted.
Design
22. Class size and responsibility — a class over ~1,000 lines or a
method over ~80 lines that the diff grows further is a design finding;
extract cohesive collaborators with their own tests rather than adding
another branch to the god class.
23. Visibility — fields private final by default; widening visibility
"for tests" is a smell (prefer package-private + same-package test).
24. Tests — JUnit tests assert behavior, not implementation; no
Thread.sleep for synchronization (use latches/awaitility); every
concurrency fix has a test that fails without it.
Anti-Patterns
Java: null returns instead of Optional · mutable public fields · deep
inheritance over composition · returning concrete types (ArrayList) from APIs ·
skipping hashCode when overriding equals · Optional for fields/params ·
manual resource close.
Scala: var and mutable collections passed around · null/.get on Option
· exceptions for control flow · non-sealed traits losing exhaustiveness · implicit
overuse.
Sources
Java Concurrency in Practice (Goetz et al.) · SEI CERT Oracle Coding Standard for Java (VNA, THI, TPS, ERR rules) · SpotBugs bug descriptions · Effective Java 3rd ed. (Bloch) · Google Java Style Guide (google.github.io/styleguide/javaguide.html) · Oracle records/sealed docs · Twitter Effective Scala (twitter.github.io/effectivescala) · scalafmt/scalafix docs.
Cross-References
pr-self-review, code-quality-architecture, sink-connector-mysql-source-of-truth.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

