agentleFS
Marisha-SahayMarisha-Sahay/awesome-java-agent-skills/skills/clean-code/java-clean-code/SKILL.md

java-clean-code

Skill24 starsChanged 3 months agoMITView on GitHub

Use when writing, refactoring or reviewing Java 21 code (classes, records, sealed types, interfaces, enums, exception handling, Javadoc), or when a Java build fails Checkstyle, JaCoCo coverage or static-analysis checks.

2 other projects use a version of this.

Adopted by

Most recently taken up by

  • Other versions2 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 2

    1. CasLubbers/code-design-skills★ 2same name
    2. nxd1184/java-clean-code-skill★ 1same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repository4 other files it gives its agents.

The file

We split this skill into the rules it gives an agent

12 rules. About 0 are common, 3 are distinctive, and 9 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every .java file must follow this exact section sequence (100-character line limit, 2-space indentation, no tabs):

    line 40
  2. Very specific:

    Virtual Threads (JEP 444): Use Executors.newVirtualThreadPerTaskExecutor() for high-concurrency I/O-bound tasks.

    line 50
  3. Very specific:

    Records (JEP 395/440): Use record for immutable data carriers and DTOs.

    line 51
  4. Very specific:

    Sealed Classes (JEP 409): Use sealed interface / sealed class to define closed type hierarchies and enable compiler-enforced exhaustive …

    line 52
  5. Very specific:

    Sequenced Collections (JEP 431): Use getFirst(), getLast(), and reversed() on ordered collections instead of manual index calculations.

    line 63
  6. Distinctive:

    Composition over Inheritance: Use delegation and Decorator wrappers rather than extending concrete classes.

    line 71
  7. Very specific:

    Generics (PECS): Use Producer-Extends, Consumer-Super (Collection<?

    line 72
  8. Very specific:

    Null Safety: Never pass or return null for collections/arrays (return List.of() or empty arrays).

    line 74
  9. Very specific:

    Resource Management: Always use try-with-resources for AutoCloseable types.

    line 81
  10. Distinctive:

    No Empty Catches or Log & Rethrow: Never leave catch blocks empty.

    line 82
  11. Very specific:

    Preserve Root Causes: Always pass the original exception as the cause when throwing custom domain exceptions (throw new …

    line 83
  12. Distinctive:

    Protect PII: Never log passwords, API keys, or personally identifiable information (PII) in error logs.

    line 84

≈ “Common” is an estimate: at least 1 in 5 of the 383,637 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Java 21 Clean Code & Engineering Standards

Overview

This skill instructs AI agents to author, refactor, and review enterprise Java code targeting Java 21 LTS. It enforces clean code, Effective Java principles, modern language capabilities (Virtual Threads, Records, Pattern Matching), and automated quality gates (Checkstyle & JaCoCo).

When to Apply

  • Writing new Java classes, records, interfaces, or unit tests.
  • Refactoring legacy Java codebases.
  • Conducting code reviews or static analysis remediation.

1. Core Architectural & Naming Standards

Naming Conventions & Anti-Patterns

IdentifierStyleFormat / RuleGood ExampleBad Anti-Pattern
Class / Interface / Record / EnumPascalCaseSpecific, intention-revealing nouns.OrderProcessingService❌ Manager, Data, IOrderService
MethodlowerCamelCaseVerb or verb phrase describing the action.calculateTotal()❌ process(), doSave()
Variable / Field / ParameterlowerCamelCaseConcise, mnemonic nouns. Avoid custom abbreviations.customerName❌ mName, custMngSys
ConstantUPPER_SNAKE_CASEstatic final deeply immutable values.MAX_RETRY_ATTEMPTS❌ maxRetry
PackageLowercaseHierarchical, concise, no underscores.com.example.order❌ com.example.order_service

Source File Layout & Ordering

Every .java file must follow this exact section sequence (100-character line limit, 2-space indentation, no tabs):

  1. Package Declaration: Single line, never line-wrapped.
  2. Import Statements: Alphabetical. Group static imports first, followed by standard imports. Wildcard imports (import java.util.*) are strictly prohibited.
  3. Class Body Member Order:
    • static final constants -> Static fields -> Instance fields (private final prioritized) -> Constructors -> Static factory methods -> Public methods -> Overloaded methods (must be contiguous) -> Private helper methods.

2. Modern Java 21 LTS Features

  • Virtual Threads (JEP 444): Use Executors.newVirtualThreadPerTaskExecutor() for high-concurrency I/O-bound tasks. Never pool virtual threads. Prefer ReentrantLock over synchronized to avoid thread pinning during blocking I/O.
  • Records (JEP 395/440): Use record for immutable data carriers and DTOs.
  • Sealed Classes (JEP 409): Use sealed interface / sealed class to define closed type hierarchies and enable compiler-enforced exhaustive pattern matching.
  • Pattern Matching for Switch (JEP 441):
    public double calculateArea(Shape shape) {
      return switch (shape) {
        case Circle(double radius) -> Math.PI * radius * radius;
        case Rectangle(double w, double h) when w > 0 && h > 0 -> w * h;
        case Square(double side) when side > 0 -> side * side;
      };
    }
  • Sequenced Collections (JEP 431): Use getFirst(), getLast(), and reversed() on ordered collections instead of manual index calculations.

3. Object Design & Clean Code Practices

  • Immutability by Default: Declare fields private final. Minimize mutable state. Return unmodifiable collections (List.of(), Set.of()) and defensive copies.
  • Creation Patterns: Favor static factory methods (of(), from()) or Builders for objects with >3 optional parameters. Implement Singletons using single-element enum.
  • Composition over Inheritance: Use delegation and Decorator wrappers rather than extending concrete classes.
  • Generics (PECS): Use Producer-Extends, Consumer-Super (Collection<? extends T> for reading, Collection<? super T> for writing).
  • Money & BigDecimal: Represent money as BigDecimal, never double or float, and build it from strings (new BigDecimal("0.10")). Compare with compareTo(...) == 0, never equals: equals also compares scale, so new BigDecimal("120").equals(new BigDecimal("120.00")) is false.
  • Null Safety: Never pass or return null for collections/arrays (return List.of() or empty arrays). Use Optional<T> strictly for method return values (never as fields or parameters).

4. Exception Handling Best Practices

  1. Throw Early, Handle Late: Validate arguments at boundaries (Objects.requireNonNull(), IllegalArgumentException). Handle exceptions at boundary layers.
  2. Resource Management: Always use try-with-resources for AutoCloseable types.
  3. No Empty Catches or Log & Rethrow: Never leave catch blocks empty. Choose to either log and resolve OR wrap and rethrow—never both (prevents log duplication).
  4. Preserve Root Causes: Always pass the original exception as the cause when throwing custom domain exceptions (throw new OrderException("Failed", cause)).
  5. Protect PII: Never log passwords, API keys, or personally identifiable information (PII) in error logs.

5. Documentation & Quality Gates

  • Javadoc: Required for all public and protected APIs. First sentence must be a concise summary ending in a period. Tag order: @param, @return, @throws, @deprecated. Always use @Override.
  • Checkstyle Enforcement: Code must compile with zero style violations (Google Style Guide, 2-space indent, K&R braces).
  • JaCoCo Quality Gates: Unit tests (JUnit 5 + AssertJ/Mockito) must maintain minimum 80% Line Coverage and 75% Branch Coverage on business logic.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.