Skip to content
cccskills
FreePublished on GitHub

java-conventions

Modern Java idioms for any JVM project (Java 17+): records, sealed types, text blocks, pattern matching, Optional discipline, streams, immutability, null safety, package layout, var usage, and code organisation. Apply when the project is a Java 17+ project. Stack-agnostic — referenced by every Java plugin in the marketplace. Use this skill to: - Write self-documenting, immutable-by-default value types with records. - Model closed type hierarchies with sealed classes and interfaces. - Handle optionality explicitly with Optional instead of returning null. - Write expressive pipelines with Stream API without performance footguns. - Lay out packages consistently (feature-first or layer-first) and keep class responsibilities tight. Do NOT use this skill for: - Framework-specific idioms (Spring annotations, JPA mappings — those live in framework plugin skills). - Build tooling (Maven/Gradle) — see java-foundation:build-tooling. - Testing patterns — see java-foundation:jvm-testing.

The English summary is being prepared. Showing the original description.

See how to install

Files included (1)

  • SKILL.md8.2 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

Java Conventions (stack-agnostic, Java 17+)

This skill encodes idioms that reduce bugs and improve readability in any Java codebase. Apply alongside the active framework plugin's conventions skill (e.g., spring-boot-plugin:spring-conventions).

Detection

Project is Java 17+ when:

  • pom.xml has <java.version>17</java.version> or <maven.compiler.source>17</maven.compiler.source> (or higher).
  • build.gradle / build.gradle.kts has sourceCompatibility = JavaVersion.VERSION_17 (or higher).

Read the build file first to learn the target Java version.

Records — prefer for value objects

Use records for immutable data carriers. They auto-generate constructor, equals, hashCode, toString.

// Prefer
public record Money(BigDecimal amount, Currency currency) {
    public Money {
        Objects.requireNonNull(amount, "amount");
        Objects.requireNonNull(currency, "currency");
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("amount must be non-negative");
        }
    }

    public Money add(Money other) {
        if (!this.currency.equals(other.currency)) {
            throw new IllegalArgumentException("Currency mismatch");
        }
        return new Money(this.amount.add(other.amount), this.currency);
    }
}

// Avoid — a plain class with no behaviour
public class Money {
    private final BigDecimal amount;
    private final Currency currency;
    // ... boilerplate constructor, getters, equals, hashCode, toString
}

Compact constructor (without parameter list) is for validation only — do not assign fields there (the canonical constructor does that).

Sealed types — model closed hierarchies

public sealed interface Shape permits Circle, Rectangle, Triangle {}

public record Circle(double radius) implements Shape {}
public record Rectangle(double width, double height) implements Shape {}
public record Triangle(double base, double height) implements Shape {}

double area(Shape shape) {
    return switch (shape) {
        case Circle c    -> Math.PI * c.radius() * c.radius();
        case Rectangle r -> r.width() * r.height();
        case Triangle t  -> 0.5 * t.base() * t.height();
    };
}

The compiler verifies exhaustiveness — no default branch needed. Add default only when genuinely required (e.g., a catch-all for unexpected extensions via --enable-preview).

Pattern matching — eliminate casting

// instanceof pattern matching (Java 16+)
if (obj instanceof String s && s.length() > 5) {
    System.out.println(s.toUpperCase());
}

// switch pattern matching (Java 21+)
String format(Object obj) {
    return switch (obj) {
        case Integer i -> "int: " + i;
        case Long l    -> "long: " + l;
        case String s  -> "str: " + s;
        case null      -> "null";
        default        -> "other: " + obj.getClass().getSimpleName();
    };
}

Never cast without an instanceof check — use pattern binding instead.

Optional — explicit optionality

// Return Optional when absence is a normal outcome
public Optional<User> findById(Long id) {
    return repository.findById(id); // JPA returns Optional
}

// Consume safely
findById(id)
    .map(User::email)
    .ifPresent(email -> sendWelcome(email));

// With fallback
String name = findById(id)
    .map(User::name)
    .orElse("Guest");

// Throwing on absence (documented expectation)
User user = findById(id)
    .orElseThrow(() -> new EntityNotFoundException("User " + id));

Avoid Optional.get() without isPresent() — defeats the purpose. Prefer orElse, orElseThrow, orElseGet, map, flatMap, ifPresent, ifPresentOrElse.

Never use Optional as a field type or method parameter — it is designed for return types only.

Streams — readable pipelines

// Prefer readable pipeline over imperative loop
List<String> activeEmails = users.stream()
    .filter(User::isActive)
    .map(User::email)
    .sorted()
    .toList();                        // Java 16+ — unmodifiable

// Collect to mutable list when mutation needed
List<String> mutable = users.stream()
    .map(User::name)
    .collect(Collectors.toCollection(ArrayList::new));

// Grouping
Map<Department, List<User>> byDept = users.stream()
    .collect(Collectors.groupingBy(User::department));

// Reduction
BigDecimal total = orders.stream()
    .map(Order::amount)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

Avoid forEach with side effects on parallel streams — use sequential streams or synchronised structures. Use parallelStream only after profiling.

Immutability

  • Prefer final fields. Make classes effectively immutable where feasible.
  • Return List.copyOf, Map.copyOf, Set.copyOf to defensive-copy mutable collections.
  • Use List.of, Map.of, Set.of for literals.
  • Never expose mutable internal state via getters — return a copy or an unmodifiable view.
public List<String> getTags() {
    return List.copyOf(this.tags);       // defensive copy
}

Null discipline

  • Annotate parameters and return types with @NonNull / @Nullable (Jakarta / JetBrains / SpotBugs — match project choice).
  • Validate at public API boundaries with Objects.requireNonNull(value, "fieldName").
  • Do not return null from public methods — use Optional, empty collections, or throw.
public User register(String email, String password) {
    Objects.requireNonNull(email, "email");
    Objects.requireNonNull(password, "password");
    // ...
}

Text blocks (Java 15+)

String json = """
        {
            "name": "%s",
            "active": true
        }
        """.formatted(user.name());

Use for multi-line SQL, JSON, HTML snippets, and test fixtures. Indent consistently with the enclosing code — the compiler strips common leading whitespace.

var — local type inference

// Good — type obvious from right-hand side
var users = new ArrayList<User>();
var result = userRepository.findAll();

// Avoid — type not obvious from right-hand side
var x = process(data);     // what type is x?

var is for local variables only. Never use it for fields, parameters, or return types.

Package layout

Choose one layout and be consistent:

Feature-first (preferred for domain-rich apps):

com.example.app/
├── user/
│   ├── User.java
│   ├── UserRepository.java
│   ├── UserService.java
│   └── UserController.java
├── order/
│   └── ...
└── shared/
    └── ...

Layer-first (acceptable for simple CRUD services):

com.example.app/
├── controller/
├── service/
├── repository/
├── model/
└── dto/

Mirror the existing project layout. Do not introduce a new layout as part of feature work.

Class design rules

  • Single Responsibility: one reason to change per class.
  • Keep public API minimal — package-private by default, public only when needed.
  • Prefer composition over inheritance for behaviour reuse.
  • Use interface to define contracts; keep implementations in the same package unless genuinely shared.
  • No static utility classes with state. Static helpers for stateless pure functions are fine.

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Angular 18-21 project structure, standalone components vs NgModule, control flow (@if/@for/@switch + *ngIf/*ngFor legacy), decorators, dependency injection (inject() function), lifecycle hooks, pipes, Angular Universal SSR pointer. Use this skill to: - Detect project style (standalone vs NgModule) and apply matching patterns. - Pick correct decorators and DI approach. - Use modern control flow (@if/@for/@switch) in Angular 17+ projects. - Apply `inject()` function over constructor injection where appropriate. - Wire bootstrap correctly (bootstrapApplication for standalone, AppModule for legacy). Do NOT use this skill for: - State management (see angular-state-and-rx). - Routing (see angular-routing). - Forms (see angular-forms). - Testing (see angular-testing).

The English summary is being prepared. Showing the original description.

AratKruglik/claude-sdlc42Updated Oct 17, 2026

Angular forms: Reactive Forms (preferred — typed FormGroup/FormControl since Angular 14, FormBuilder, custom + async validators, FormArray, multi-step) and Template-driven (`[(ngModel)]` + FormsModule). Validation strategies, server error mapping, accessibility. Use this skill to: - Build Reactive Forms with typed FormGroup/FormControl. - Use FormBuilder для concise syntax. - Implement custom synchronous and async validators. - Wire FormArray for dynamic field lists. - Map server errors back to form fields. - Pick Reactive vs Template-driven (prefer Reactive). Do NOT use this skill for: - General conventions (see angular-conventions). - State management beyond forms (see angular-state-and-rx). - Routing (see angular-routing). - Testing forms (see angular-testing).

The English summary is being prepared. Showing the original description.

AratKruglik/claude-sdlc42Updated Oct 17, 2026

Angular Router (built-in `@angular/router`) — route configuration for standalone and NgModule projects, functional guards (Angular 14.1+), lazy loading, route resolvers, typed params via signals/observables, programmatic navigation, route data and meta. Use this skill to: - Configure routes (standalone-style or NgModule-style). - Use functional guards (canActivate as function, preferred over class-based in 17+). - Lazy-load components or feature modules. - Implement auth guards via route meta + functional guards. - Read params/queries via `inject(ActivatedRoute)` + signals or RxJS. Do NOT use this skill for: - General conventions (see angular-conventions). - State management (see angular-state-and-rx). - Forms (see angular-forms). - Testing routes (see angular-testing).

The English summary is being prepared. Showing the original description.

AratKruglik/claude-sdlc42Updated Oct 17, 2026

State management for Angular 18-21: signals (signal/computed/effect), services-as-state, NgRx Store + Effects + Selectors, NgRx Component Store, NgRx Signals (newer signal-based store). RxJS essentials — operators, async pipe, takeUntilDestroyed, signal/observable interop. Use this skill to: - Pick the right state tool (signals / services / NgRx variant / vue-query equivalent). - Use signals correctly (signal/computed/effect — when each). - Build a Pinia-style service-as-state singleton. - Set up NgRx Store + Effects + Selectors. - Use RxJS without leaking subscriptions (async pipe, takeUntilDestroyed, Subject patterns). - Bridge signals ↔ observables via toSignal / toObservable. Do NOT use this skill for: - General Angular conventions (see angular-conventions). - Routing state (see angular-routing). - Form state (see angular-forms). - Testing state (see angular-testing).

The English summary is being prepared. Showing the original description.

AratKruglik/claude-sdlc42Updated Oct 17, 2026

Testing Angular 18-21: TestBed, component harnesses (@angular/cdk/testing), Karma+Jasmine (default historical) vs Jest (jest-preset-angular, modern), Angular Testing Library (RTL-style). HttpClient mocking via HttpTestingController. NgRx Effects testing. Cypress / Playwright e2e. Use this skill to: - Detect runner (Karma+Jasmine vs Jest) and configure correctly. - Write component tests with TestBed. - Use component harnesses for Material / custom UI components. - Mock HttpClient via provideHttpClientTesting + HttpTestingController. - Test signal-based inputs with componentRef.setInput(). - Test NgRx Effects with provideMockActions. Do NOT use this skill for: - General Angular conventions (see angular-conventions). - Routing patterns broadly (see angular-routing — covers testing routes briefly). - Form patterns broadly (see angular-forms).

The English summary is being prepared. Showing the original description.

AratKruglik/claude-sdlc42Updated Oct 17, 2026

Shared conventions for every SDLC development-phase architect agent: hard rules, code quality bar, workflow steps (superpowers invocation, spec reading, codebase exploration, verification), and the report/compact-summary contract. Architects load this skill first, then apply their stack-specific instructions on top.

The English summary is being prepared. Showing the original description.

AratKruglik/claude-sdlc42Updated Oct 17, 2026

See all skills by AratKruglik

Report a problem with this skill