Communitygithub.com

Java コーディング規約

Spring Boot および Quarkus サービス向けの Java コーディング規約。命名、不変性、Optional の使用法、ストリーム、例外、ジェネリクス、CDI、リアクティブパターン、プロジェクト構成を自動的に適用します。Spring Boot または Quarkus サービスでコードを作成・レビューする際に使用してください。

Java コーディング規約 とは?

このスキルは、Spring Boot または Quarkus フレームワークを使用する Java 17+ プロジェクトにおいて、可読性が高く保守性に優れたコードを記述するための包括的なコーディング規約を提供します。ビルドファイルを自動解析して Spring Boot または Quarkus のいずれのフレームワークが使用されているかを検出し、検出結果に基づいてフレームワーク固有の規約を適用します。コア原則として、明確さの優先、デフォルトでの不変性(immutable)、フェイルファスト、一貫性のある命名とパッケージ構造を掲げています。具体的には、命名規則(PascalCase、camelCase、UPPER_SNAKE_CASE)、不変性(レコード、final フィールドの推奨)、Optional の適切な使用法、ストリームのベストプラクティス、依存性注入(コンストラクタインジェクション vs フィールドインジェクション)、リアクティブパターン(Uni/Multi)、例外処理(ドメイン固有例外、集中ハンドリング)、ジェネリクスと型安全性、プロジェクト構造(Spring Boot と Quarkus それぞれの推奨ディレクトリ構成)、ロギング(SLF4J vs JBoss Logging)、null 値の処理、設定(@ConfigurationProperties vs @ConfigMapping)、テスト手法(JUnit 5、AssertJ、Mockito、@WebMvcTest、@QuarkusTest)などをコード例とともに詳細に解説しています。このスキルは、Claude Code や Cursor などの AI エージェントが Java コードを生成またはレビューする際に、プロジェクトのフレームワークを自動認識し、適切なコーディング規約を自動的に適用することを可能にします。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/java-coding-standards

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Java コーディング規約 は何をしますか?

Spring Boot および Quarkus サービスにおける、読みやすく保守性の高い Java (17+) コードのための規約。

使用タイミング

  • Spring Boot または Quarkus プロジェクトで Java コードを作成・レビューする場合
  • 命名、不変性、例外処理の規約を適用する場合
  • レコード、sealed クラス、パターンマッチング (Java 17+) を使用する場合
  • Optional、ストリーム、ジェネリクスの使用方法をレビューする場合
  • パッケージとプロジェクト構造を整理する場合
  • [QUARKUS]: CDI スコープ、Panache エンティティ、リアクティブパイプラインを扱う場合

動作の仕組み

フレームワーク検出

規約を適用する前に、ビルドファイルからフレームワークを特定します。

  • ビルドファイルに quarkus が含まれる → [QUARKUS] の規約を適用
  • ビルドファイルに spring-boot が含まれる → [SPRING] の規約を適用
  • いずれも検出されない → 共通の規約のみを適用

コア原則

  • 技巧的であることよりも明確さを優先する
  • デフォルトで不変(immutable)にし、共有可変状態を最小限にする
  • 意味のある例外でフェイルファスト(fail fast)にする
  • 一貫した命名とパッケージ構造
  • [QUARKUS]: 実行時処理よりもビルド時処理を優先し、可能な限り実行時リフレクションを避ける

例

以下のセクションでは、Spring Boot、Quarkus、および共通の Java に関する具体的な例を示します。 命名、不変性、依存性注入、リアクティブコード、例外、プロジェクト構成、ロギング、設定、テストについて説明します。

命名

// PASS: クラス/レコード: PascalCase
public class MarketService {}
public record Money(BigDecimal amount, Currency currency) {}

// PASS: メソッド/フィールド: camelCase
private final MarketRepository marketRepository;
public Market findBySlug(String slug) {}

// PASS: 定数: UPPER_SNAKE_CASE
private static final int MAX_PAGE_SIZE = 100;

// PASS: [QUARKUS] JAX-RS リソースは *Resource と命名し、*Controller とはしない
public class MarketResource {}

// PASS: [SPRING] REST コントローラーは *Controller と命名する
public class MarketController {}

不変性

// PASS: レコードと final フィールドを優先
public record MarketDto(Long id, String name, MarketStatus status) {}

public class Market {
  private final Long id;
  private final String name;
  // getter のみ、setter はなし
}

// PASS: [QUARKUS] Panache アクティブレコードエンティティは public フィールドを使用する(Quarkus の慣例)
@Entity
public class Market extends PanacheEntity {
  public String name;
  public MarketStatus status;
  // Panache はビルド時にアクセサを生成するため、public フィールドが慣用的
}

// PASS: [QUARKUS] Panache MongoDB エンティティ
@MongoEntity(collection = "markets")
public class Market extends PanacheMongoEntity {
  public String name;
  public MarketStatus status;
}

Optional の使用法

// PASS: find* メソッドからは Optional を返す
// [SPRING]
Optional<Market> market = marketRepository.findBySlug(slug);

// [QUARKUS] Panache
Optional<Market> market = Market.find("slug", slug).firstResultOptional();

// PASS: get() の代わりに map/flatMap を使用
return market
    .map(MarketResponse::from)
    .orElseThrow(() -> new EntityNotFoundException("Market not found"));

ストリームのベストプラクティス

// PASS: 変換にストリームを使用し、パイプラインは短く保つ
List<String> names = markets.stream()
    .map(Market::name)
    .filter(Objects::nonNull)
    .toList();

// FAIL: 複雑なネストされたストリームは避け、明確さのためにループを優先する

依存性注入

// PASS: [SPRING] コンストラクタインジェクション(フィールドへの @Autowired よりも優先)
@Service
public class MarketService {
  private final MarketRepository marketRepository;

  public MarketService(MarketRepository marketRepository) {
    this.marketRepository = marketRepository;
  }
}

// PASS: [QUARKUS] コンストラクタインジェクション
@ApplicationScoped
public class MarketService {
  private final MarketRepository marketRepository;

  @Inject
  public MarketService(MarketRepository marketRepository) {
    this.marketRepository = marketRepository;
  }
}

// PASS: [QUARKUS] パッケージプライベートフィールドインジェクション(Quarkus では許容 — プロキシ問題を回避)
@ApplicationScoped
public class MarketService {
  @Inject
  MarketRepository marketRepository;
}

// FAIL: [SPRING] @Autowired を使用したフィールドインジェクション
@Autowired
private MarketRepository marketRepository; // コンストラクタインジェクションを使用すること

// FAIL: [QUARKUS] インターセプションや遅延初期化が必要な場合の @Singleton
@Singleton // プロキシ不可 — 代わりに @ApplicationScoped を使用
public class MarketService {}

リアクティブパターン [QUARKUS]

// PASS: リアクティブエンドポイントからは Uni/Multi を返す
@GET
@Path("/{slug}")
public Uni<Market> findBySlug(@PathParam("slug") String slug) {
  return Market.find("slug", slug)
      .<Market>firstResult()
      .onItem().ifNull().failWith(() -> new MarketNotFoundException(slug));
}

// PASS: ノンブロッキングパイプラインの構成
public Uni<OrderConfirmation> placeOrder(OrderRequest req) {
  return validateOrder(req)
      .chain(valid -> persistOrder(valid))
      .chain(order -> notifyFulfillment(order));
}

// FAIL: Uni/Multi パイプライン内でのブロッキング呼び出し
public Uni<Market> find(String slug) {
  Market m = Market.find("slug", slug).firstResult(); // BLOCKING — イベントループを壊す
  return Uni.createFrom().item(m);
}

// FAIL: 共有された Uni への複数回の subscribe
Uni<Market> shared = fetchMarket(slug);
shared.subscribe().with(m -> log(m));
shared.subscribe().with(m -> cache(m)); // 二重 subscribe — Uni.memoize() を使用すること

例外

  • ドメインエラーには非チェック例外を使用し、技術的例外にはコンテキストを付与してラップする
  • ドメイン固有の例外を作成する(例: MarketNotFoundException)
  • 広範な catch (Exception ex) は、中央で再スローまたはロギングする場合を除き避ける
throw new MarketNotFoundException(slug);

集中例外処理

// [SPRING]
@RestControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(MarketNotFoundException.class)
  public ResponseEntity<ErrorResponse> handle(MarketNotFoundException ex) {
    return ResponseEntity.status(404).body(ErrorResponse.from(ex));
  }
}

// [QUARKUS] オプション A: ExceptionMapper
@Provider
public class MarketNotFoundMapper implements ExceptionMapper<MarketNotFoundException> {
  @Override
  public Response toResponse(MarketNotFoundException ex) {
    return Response.status(404).entity(ErrorResponse.from(ex)).build();
  }
}

// [QUARKUS] オプション B: @ServerExceptionMapper (RESTEasy Reactive)
@ServerExceptionMapper
public RestResponse<ErrorResponse> handle(MarketNotFoundException ex) {
  return RestResponse.status(Status.NOT_FOUND, ErrorResponse.from(ex));
}

ジェネリクスと型安全性

  • ロータイプ(raw type)を避け、ジェネリックパラメータを宣言する
  • 再利用可能なユーティリティには境界ワイルドカードを優先する
public <T extends Identifiable> Map<Long, T> indexById(Collection<T> items) { ... }

プロジェクト構造

[SPRING] Maven/Gradle

src/main/java/com/example/app/
  config/
  controller/
  service/
  repository/
  domain/
  dto/
  util/
src/main/resources/
  application.yml
src/test/java/... (main をミラー)

[QUARKUS] Maven/Gradle

src/main/java/com/example/app/
  config/              # @ConfigMapping, @ConfigProperty Bean, Producer
  resource/            # JAX-RS リソース ("controller" ではない)
  service/
  repository/          # PanacheRepository の実装(アクティブレコードを使用しない場合)
  domain/              # JPA/Panache エンティティ、MongoDB エンティティ
  dto/
  util/
  mapper/              # MapStruct マッパー(使用する場合)
src/main/resources/
  application.properties   # Quarkus の慣例(quarkus-config-yaml で YAML もサポート)
  import.sql               # 開発/テスト用の Hibernate 自動インポート
src/test/java/... (main をミラー)

書式とスタイル

  • 2 または 4 スペースを一貫して使用する(プロジェクト標準に従う)
  • 1 ファイルに 1 つの public トップレベル型
  • メソッドは短く焦点を絞り、ヘルパーを抽出する
  • メンバーの順序: 定数、フィールド、コンストラクタ、public メソッド、protected、private

回避すべきコードスメル

  • 長いパラメータリスト → DTO/ビルダーを使用
  • 深いネスト → 早期リターン
  • マジックナンバー → 名前付き定数
  • 静的で可変な状態 → 依存性注入を優先
  • サイレントな catch ブロック → ログに記録して対処するか、再スロー
  • [QUARKUS]: @ApplicationScoped が意図されているところでの @Singleton — プロキシとインターセプションを壊す
  • [QUARKUS]: quarkus-resteasy-reactive と quarkus-resteasy (クラシック) の混在 — どちらか一方のスタックを選択
  • [QUARKUS]: 同じ境界コンテキスト内での Panache アクティブレコードとリポジトリパターンの混在 — どちらか一方を選択

ロギング

// [SPRING] SLF4J
private static final Logger log = LoggerFactory.getLogger(MarketService.class);
log.info("fetch_market slug={}", slug);
log.error("failed_fetch_market slug={}", slug, ex);

// [QUARKUS] JBoss Logging(デフォルト、ビルド時にゼロコスト)
private static final Logger log = Logger.getLogger(MarketService.class);
log.infof("fetch_market slug=%s", slug);
log.errorf(ex, "failed_fetch_market slug=%s", slug);

// [QUARKUS] 代替: @Inject による簡略化されたロギング
@Inject
Logger log; // CDI インジェクション、宣言クラスにスコープ

Null 処理

  • やむを得ない場合のみ @Nullable を受け入れ、それ以外は @NonNull を使用
  • 入力には Bean Validation (@NotNull, @NotBlank) を使用
  • [QUARKUS]: @BeanParam、@RestForm、リクエストボディパラメータに @Valid を適用

設定

// [SPRING] @ConfigurationProperties
@ConfigurationProperties(prefix = "market")
public record MarketProperties(int maxPageSize, Duration cacheTtl) {}

// [QUARKUS] @ConfigMapping(型安全、ビルド時に検証)
@ConfigMapping(prefix = "market")
public interface MarketConfig {
  int maxPageSize();
  Duration cacheTtl();
}

// [QUARKUS] @ConfigProperty による単純な値
@ConfigProperty(name = "market.max-page-size", defaultValue = "100")
int maxPageSize;

テストの期待事項

共通

  • JUnit 5 + AssertJ(流暢なアサーション用)
  • Mockito によるモッキング、可能な限り部分モックは避ける
  • 決定論的なテストを優先し、隠れたスリープは避ける

[SPRING]

  • コントローラースライスには @WebMvcTest、リポジトリースライスには @DataJpaTest
  • @SpringBootTest は完全な統合テスト用に予約
  • Spring コンテキストでの Bean 置き換えには @MockBean

[QUARKUS]

  • 単体テストにはプレーンな JUnit 5 + Mockito(@QuarkusTest は不要)
  • @QuarkusTest は CDI 統合テスト用に予約
  • CDI Bean の統合テストでの置き換えには @InjectMock
  • データベース/Kafka/Redis には Dev Services — Dev Services で十分な場合は手動の Testcontainers セットアップを避ける
  • カスタム外部サービスライフサイクルには @QuarkusTestResource
// [SPRING] コントローラーテスト
@WebMvcTest(MarketController.class)
class MarketControllerTest {
  @Autowired MockMvc mockMvc;
  @MockBean MarketService marketService;
}

// [QUARKUS] 統合テスト
@QuarkusTest
class MarketResourceTest {
  @InjectMock
  MarketService marketService;

  @Test
  void should_return_404_when_market_not_found() {
    given().when().get("/markets/unknown").then().statusCode(404);
  }
}

// [QUARKUS] 単体テスト(CDI なし、@QuarkusTest なし)
@ExtendWith(MockitoExtension.class)
class MarketServiceTest {
  @Mock MarketRepository marketRepository;
  @InjectMocks MarketService marketService;
}

覚えておいてください: コードは意図的で、型付けされ、観測可能であることを心がけましょう。マイクロ最適化よりも保守性を優先し、それが証明された場合にのみ最適化を行ってください。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル