java-idioms
Skill157 starsChanged 3 months agoMITView on GitHub
Modern Java (17/21+ LTS) idioms: records, sealed classes, pattern matching switch, Optional hygiene, streams, and JUnit 5 testing. Use when writing, refactoring, or reviewing Java core logic, domain models, or libraries. Pair with spring-boot-idioms for Spring services.
In this repository59 other files it gives its agents.
- github-pages/agents.mdAGENTS.md
- adrSkill
- agent-protocolsSkill
- angular-idiomsSkill
- api-documentationSkill
- axum-idiomsSkill
- browser-automationSkill
- chaos-testingSkill
- ci-cdSkill
- cli-developmentSkill
- code-auditSkill
- code-reviewSkill
- cpp-idiomsSkill
- csharp-idiomsSkill
- data-engineeringSkill
- debugging-protocolSkill
- django-idiomsSkill
- dotnet-idiomsSkill
- elixir-idiomsSkill
- embedded-systemsSkill
- feature-flagsSkill
- flutter-idiomsSkill
- frontend-designSkill
- git-commit-integritySkill
- go-idiomsSkill
- guardrailsSkill
- hono-idiomsSkill
- incident-responseSkill
- javascript-idiomsSkill
- kotlin-idiomsSkill
- laravel-idiomsSkill
- logging-implementationSkill
- ml-engineeringSkill
- mobile-designSkill
- mobile-testingSkill
- nextjs-idiomsSkill
- parallel-dispatchSkill
- payment-integrationSkill
- perf-optimizationSkill
- php-idiomsSkill
- postgres-idiomsSkill
- python-idiomsSkill
- rails-idiomsSkill
- react-idiomsSkill
- refactoring-patternsSkill
- research-methodologySkill
- ruby-idiomsSkill
- rust-idiomsSkill
- security-auditSkill
- sequential-thinkingSkill
- spring-boot-idiomsSkill
- sql-idiomsSkill
- structured-specSkill
- supply-chain-securitySkill
- swift-idiomsSkill
- testability-patternsSkill
- testing-strategySkill
- typescript-idiomsSkill
- vue-idiomsSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is 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.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 152
Must pass zero warnings/errors before commit.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 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
Java Idioms and Patterns
Java rewards clarity, type safety, and robust ecosystem tooling. Modern Java (17+ LTS) favors records, sealed classes, and pattern matching. Idiomatic Java = clean, readable, framework-aware.
Scope: Java coding idioms. Test naming: .agents/rules/testing-strategy.md. Logging:
@.agents/skills/logging-implementation/SKILL.md.
Modern Java Features (17+ LTS)
- Records for immutable data carriers:
// ✅ Concise, immutable, auto-generated equals/hashCode/toString public record CreateTaskRequest(String title, Priority priority) {} // ❌ Verbose boilerplate POJO public class CreateTaskRequest { /* getters, setters, equals, hashCode... */ } - Sealed classes for constrained hierarchies:
public sealed interface TaskResult permits Success, Failure, Pending {} public record Success(Task task) implements TaskResult {} public record Failure(String reason) implements TaskResult {} public record Pending(String taskId) implements TaskResult {} - Pattern matching with
switch:return switch (result) { case Success(var task) -> ResponseEntity.ok(task); case Failure(var reason) -> ResponseEntity.badRequest().body(reason); case Pending(var id) -> ResponseEntity.accepted().body(id); }; - Text blocks for queries and templates:
String query = """ SELECT t.id, t.title, t.priority FROM tasks t WHERE t.user_id = ? ORDER BY t.created_at DESC """; - Virtual threads (21+) for I/O-bound work:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> fetchUser(userId)); executor.submit(() -> fetchTasks(userId)); }
Error Handling
- Domain exception hierarchies — never raw
Exception:public abstract class DomainException extends RuntimeException { protected DomainException(String message) { super(message); } } public class NotFoundException extends DomainException { private final String resource; private final String resourceId; public NotFoundException(String resource, String resourceId) { super(String.format("%s '%s' not found", resource, resourceId)); this.resource = resource; this.resourceId = resourceId; } } - Never catch
Exceptionbroadly — catch specific exceptions. Never swallow exceptions silently. Optionalfor nullable returns — never for parameters:// ✅ Return type public Optional<Task> findById(String id) { ... } // ❌ Parameter — use overloading or @Nullable instead public void process(Optional<String> filter) { ... }
Interfaces and DI
- Program to interfaces, inject via constructor:
// ✅ Interface in consumer package public interface TaskStorage { Task getById(String id); void save(Task task); } // ✅ Constructor injection (Spring auto-wires) @Service public class TaskService { private final TaskStorage storage; public TaskService(TaskStorage storage) { this.storage = storage; } } - Prefer constructor injection over
@Autowiredfield injection. No field injection — ever.
Naming
- PascalCase for classes, interfaces, enums, records.
- camelCase for methods, fields, local variables.
- UPPER_SNAKE_CASE for constants (
static final). - No Hungarian notation.
TaskServicenotITaskService.userIdnotstrUserId. - Package names: lowercase, no underscores.
com.example.tasknotcom.example.task_management.
Testing
Test naming, pyramid: .agents/rules/testing-strategy.md. Java-specific tooling below.
- JUnit 5 + AssertJ:
@Test void calculateDiscount_returnsZero_whenNoItems() { var result = calculator.calculateDiscount(List.of(), coupon); assertThat(result).isEqualTo(0.0); } @ParameterizedTestfor table-driven tests:@ParameterizedTest @CsvSource({"low,1", "medium,5", "high,10"}) void priorityScore_mapsCorrectly(String priority, int expected) { assertThat(Priority.score(priority)).isEqualTo(expected); }- Mockito for mocking — never PowerMock:
@ExtendWith(MockitoExtension.class) class TaskServiceTest { @Mock TaskStorage storage; @InjectMocks TaskService service; } - TestContainers for integration tests — real DB, no in-memory substitutes for critical paths.
Formatting and Static Analysis
Must pass zero warnings/errors before commit. See .agents/rules/code-idioms-and-conventions.md.
| Tool | Purpose | Command |
google-java-format | Canonical formatting | google-java-format --replace src/**/*.java |
SpotBugs | Bug detection | mvn spotbugs:check or gradle spotbugsMain |
Error Prone | Compile-time bug detection | Compiler plugin |
Checkstyle | Style enforcement | mvn checkstyle:check |
SonarQube | Comprehensive analysis | CI integration |
OWASP Dependency-Check | CVE scanning | mvn dependency-check:check |
Related
- Code Idioms and Conventions .agents/rules/code-idioms-and-conventions.md
- Testing Strategy .agents/rules/testing-strategy.md
- Error Handling Principles .agents/rules/error-handling-principles.md
- Dependency Management Principles @.agents/rules/dependency-management-principles.md
- Logging Implementation @.agents/skills/logging-implementation/SKILL.md
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.

