agentleFS
iadr-deviadr-dev/kotlin-claude-workflow/.claude/skills/kotlin-architecture/SKILL.md

kotlin-architecture

Skill1 starsChanged 40 days agoMITView on GitHub

Use when creating modules, adding a feature that spans layers, deciding where code belongs or how to name and organize folders, packages and files, reviewing a change for architecture/maintainability/scalability, setting up code standards or quality gates (detekt, ktlint, Kover, dependency rules), or judging architecture metrics. Covers clean architecture, modularization, and code-quality thresholds for Android, Kotlin Multiplatform, and JVM backend projects. Complements the Kotlin/Compose skills (kotlin-*, compose-*), which own code-level Kotlin/Compose decisions.

The file

Show its rules and text

We split this skill into the rules it gives an agent

13 rules. About 0 are common, 5 are distinctive, and 8 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 8

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Add one when any is true:

    line 48
  2. Distinctive:

    Don't create a use case per repository method "for consistency".

    line 58
  3. Very specific:

    Use-case conventions: verb-first name (GetX, ObserveX, PlaceOrder), one public operator fun invoke, suspend for one-shot work and Flow for …

    line 61
  4. Very specific:

    JVM backend: no UiState/ViewModel. Route/Controller → UseCase (service) → Repository → DataSource.

    line 70
  5. Distinctive:

    Default module graph (scale down for small projects.

    line 83
  6. Very specific:

    Prefer implementation over api.

    line 101
  7. Distinctive:

    Follow Kotlin coding conventions.

    line 107
  8. Very specific:

    Every @Suppress(...) and every detekt/lint baseline entry carries an inline reason and is named in the report.

    line 116
  9. Very specific:

    No secrets in source, BuildConfig or committed files.

    line 117
  10. Very specific:

    Use these as review findings and as detekt/Kover gates.

    line 121
  11. Distinctive:

    Do metrics in §4 still hold for touched files?

    line 160
  12. Very specific:

    Do new files follow §8 (package matches path, file named after its main type, no catch-all Utils, no package past ~15 files)?

    line 162
  13. Very specific:

    When the project lacks them, propose (don't silently add) the setup in references/quality-gates.md: Spotless + ktlint, detekt config, …

    line 166

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

Kotlin architecture and code quality

Architecture rules decide where code lives and what may depend on what. Code-level decisions (Flow design, when, Compose state) stay with the kotlin-* and compose-* skills; load those for the code inside each layer.

1. Layers and the dependency rule

Call flow and data flow

 PRESENTATION                         DOMAIN                         DATA
┌──────────────┐ events ┌───────────┐ calls ┌──────────┐ calls ┌────────────────────┐ calls ┌──────────────┐
│ UI           │──────▶│ ViewModel │──────▶│ UseCase  │──────▶│ Repository         │──────▶│ DataSource   │
│ (Composable) │       │ (state    │       │(optional)│       │ interface (domain) │       │ remote/local │
│              │◀──────│  holder)  │◀──────│          │◀──────│ impl (data)        │◀──────│ (Retrofit,   │
└──────────────┘ UiState└───────────┘domain └──────────┘domain └────────────────────┘ DTO / │ Ktor, Room,  │
                  (StateFlow)         models             models                  entity │ DataStore)   │
                                                                                        └──────────────┘
Compile-time dependencies: presentation → domain ← data   (data implements domain's interfaces)

Events go down (user action → ViewModel function → use case/repository). State comes up (data source → repository maps to domain model → ViewModel maps to UiState → UI renders). This is unidirectional data flow (UDF).

What each piece owns

PieceLayer / moduleOwnsMust not
UI (composables, screens)presentation, :feature:xrendering UiState, forwarding user events as lambdas, UI-only state (scroll, focus, animation, text field drafts)call repositories/use cases, hold business logic, know DTOs
UiStatepresentation, :feature:xan immutable snapshot of everything the screen shows: data class XUiState(...) or a sealed Loading / Content / Error; already formatted for displaycontain DTOs/entities, mutable collections, Context, framework types
UI event / effectpresentationone-off outcomes (navigate, show snackbar) — prefer modeling them as state that the UI consumes (see compose-state-and-effects, kotlin-concurrency-and-flow)be a hot SharedFlow without replay rules
ViewModel (state holder)presentation, :feature:xexposing StateFlow<UiState>, handling events, mapping domain models/errors → UiState, screen-level coroutine scopedo I/O directly, reference Views/Context/composables, expose MutableStateFlow
UseCase (optional)domain, :core:domain or :feature:x:domainone business operation: class GetVisibleOrdersUseCase { operator fun invoke(...) }; pure Kotlin, testable without Androidbe a pass-through; hold state; depend on data implementations
Domain modeldomainentities and value classes with business meaning (OrderId, Money), domain errors (sealed)carry serialization/DB annotations
Repository interfacedomainthe contract the app needs (fun observeOrders(): Flow<List<Order>>)leak where data comes from
Repository implementationdata, :core:datasingle source of truth, caching/offline policy, merging remote + local, mapping DTO/entity → domain, exception → domain error, dispatcher selectionexpose DTOs, be called from UI directly
DataSourcedataone source each: OrdersRemoteDataSource (Retrofit/Ktor), OrdersLocalDataSource (Room/SQLDelight/DataStore); DTOs and entitiescontain business rules

When to add a UseCase

Add one when any is true:

  1. Combines several repositories (e.g. orders + user settings → visible orders).
  2. Holds a business rule worth testing on its own (validation, pricing, permission checks, sorting/filtering by business meaning).
  3. Reused by two or more ViewModels (or by ViewModel + background worker/server route).
  4. Long or multi-step operation that would bloat the ViewModel (checkout: validate → reserve → pay → confirm).
  5. The project is a KMP project and the logic must be shared across platforms' presentation layers.

Skip it (ViewModel calls the repository directly) when the operation is a single repository call with no logic — observeOrders(), getUser(id). Don't create a use case per repository method "for consistency"; if the project already mandates that, follow the project's existing convention.

Use-case conventions: verb-first name (GetX, ObserveX, PlaceOrder), one public operator fun invoke, suspend for one-shot work and Flow for streams, inject dispatchers rather than hard-coding them, return domain types or a sealed result.

Variations by project type

  • Android app: exactly the diagram. ViewModel = androidx.lifecycle.ViewModel.
  • KMP: domain + data in commonMain (Ktor, SQLDelight/Room KMP, DataStore); ViewModel in commonMain with the KMP lifecycle-viewmodel artifact or a plain state holder; only UI and platform data sources live in platform source sets.
  • JVM backend: no UiState/ViewModel. Route/Controller → UseCase (service) → Repository → DataSource. Request/response DTOs live in the delivery layer and are mapped at its edge; use cases are usually justified here because most endpoints carry business rules and transactions.
  • Small app/prototype: domain may be a package inside one module instead of a separate module; keep the dependency direction anyway so it can be split later.

Rules

  • Domain is pure Kotlin. In KMP it lives in commonMain; on Android it is a kotlin("jvm") or KMP module, never an Android library.
  • DTOs and DB entities never cross into domain or UI; map at the data boundary. Domain models are mapped to UiState in the ViewModel (or a small presentation mapper).
  • Errors: data layer converts exceptions into domain errors (sealed type or Result); ViewModel maps them to user-facing UiState; presentation never catches IOException/SQLException.
  • DI (Hilt/Koin/Metro/Spring) wires implementations at the app/composition root. Domain has no DI annotations other than @Inject constructor where the project already allows it.
  • Tests per layer: UseCase and repository with fakes (:core:testing), ViewModel with fake repositories + runTest/Turbine, UI with compose-ui-testing-patterns.

2. Modularization

Default module graph (scale down for small projects; don't create empty modules):

:app                       (Android app / server main / KMP host apps)
:feature:<name>            UI + state holders for one user-facing feature
   └─ optionally :feature:<name>:api + :impl when other features must navigate to/consume it
:core:domain               shared entities, repository interfaces
:core:data                 repository impls, network, database
:core:ui / :core:designsystem   shared composables, theme
:core:testing              fakes, test rules, fixtures
build-logic/               convention plugins (included build)

Rules:

  • :feature:* never depends on another :feature:* implementation — only on its :api module or via navigation contracts.
  • :core:* never depends on :feature:*.
  • Shared build config goes in build-logic convention plugins (<proj>.android.library, <proj>.kmp.library, <proj>.jvm.library, <proj>.detekt), not copy-pasted blocks. Versions only in gradle/libs.versions.toml.
  • Prefer implementation over api; use api only when a type from the dependency appears in the module's public signatures.
  • Mark everything internal by default; public only what other modules use. Library modules use explicitApi().
  • Split a module when: it exceeds ~10k LOC, two teams edit it, or a change in it rebuilds many unrelated modules. Merge modules that always change together.

3. Code standards

  • Follow Kotlin coding conventions; Android projects also follow the Android Kotlin style guide.
  • Formatting is enforced by tools, never by review: ktlint (or ktfmt) via Spotless, with .editorconfig committed.
  • Static analysis: detekt with the project config/detekt/detekt.yml (template in references/quality-gates.md); Android lint for Android modules. New code adds no new baseline entries.
  • Naming: packages by feature (com.x.feature.login), not by type (com.x.viewmodels). Classes are nouns, functions verbs, booleans is/has/should. Folder layout, package roots, file naming and split triggers: §8.
  • No !! outside tests; no lateinit for values that can be constructor parameters; no GlobalScope; no mutable public state (MutableStateFlow exposed publicly).
  • Immutability first: val, read-only collections, data class copies for state.
  • Public APIs get KDoc when the behavior is not obvious from the name and types.
  • Reuse before writing: search the modules for an existing function, type or mapper that already does the job and name what was reused. Extract duplicated logic on the third copy (on the second when both must change together); keep look-alike code separate when the copies change for different reasons.
  • A new library or Gradle plugin is the person's decision: first check the Kotlin standard library and existing dependencies, then name the addition and its reason in the report. Never add one silently.
  • Every @Suppress(...) and every detekt/lint baseline entry carries an inline reason and is named in the report.
  • No secrets in source, BuildConfig or committed files. Tokens are stored encrypted with a key from the Android Keystore, never in plain preferences or DataStore. Logs carry no tokens or personal data, and an error is logged once, where it is handled.

4. Quality metrics and thresholds

Use these as review findings and as detekt/Kover gates. Exceeding one is a finding to justify or fix, not an automatic rewrite. references/quality-gates.md has the tested setup; note that the detekt rules that need type resolution (InjectDispatcher, UnsafeCallOnNullableType) only run if the typed detekt tasks are attached to check, which its convention plugin does (the task names per project type are listed in the detekt bullet of its CI template section).

MetricThresholdTool
Cyclomatic complexity per function≤ 15 (> 10 is a review smell; detekt has no separate warning level)detekt CyclomaticComplexMethod
Cognitive complexity per function≤ 15detekt CognitiveComplexMethod
Function length≤ 60 linesdetekt LongMethod
Class length≤ 600 linesdetekt LargeClass
Parameters≤ 6 function / 7 constructor (composables exempt for modifiers/slots)detekt LongParameterList
Nesting depth≤ 4detekt NestedBlockDepth
Functions per class / file≤ 20 non-private each (ignorePrivate still counts internal)detekt TooManyFunctions
File length≤ 500 linesreview (detekt LargeClass measures class length)
Test coverage (line)domain ≥ 80%, data ≥ 70%, every other module ≥ 60% (a per-module coverage.minLine property); an overall figure needs a root aggregation project; "changed lines covered" is a review itemKover koverVerify
Module dependency rulezero violations of §1/§2review, ./gradlew :app:dependencies, or a module-graph assertion plugin
Public API drift (libraries)zero unreviewed changesBCV apiCheck, Kotlin checkKotlinAbi or Metalava
Build healthno new compiler warnings; allWarningsAsErrors in CI where feasibleKotlin compiler

5. Performance (architecture-level)

  • Android startup/runtime: Baseline Profiles (:baselineprofile module), R8 full mode in release (r8-analyzer skill for keep rules), lazy DI for heavy graphs, no disk/network on main thread (StrictMode in debug).
  • Compose: stable UI state models (immutable, @Immutable/@Stable only when true); defer to compose-performance for diagnosis.
  • Coroutines: inject dispatchers (never hard-code Dispatchers.IO in classes); defer to kotlin-concurrency-and-flow.
  • Data: paging for unbounded lists, caching policy defined in repositories, DB queries off main thread and indexed. Network clients set explicit timeouts; retries use bounded backoff and only wrap operations that are safe to run twice.
  • Database migrations: never edit a migration that has shipped. Every schema version bump ships with a migration and a test that upgrades from the previous schema: Room with exportSchema on, the exported schema directory committed and a MigrationTestHelper test; SQLDelight with a schemaOutputDirectory, the committed .db files and verifyMigrations on, so verifySqlDelightMigration runs in check. fallbackToDestructiveMigration in a released app wipes user data; it needs the person's explicit approval.
  • JVM server: non-blocking I/O in Ktor handlers, connection pools sized explicitly, no N+1 queries.
  • Build performance: configuration cache + build cache on, convention plugins, no allprojects {} / cross-project configuration, KSP over kapt.
  • Measure before optimizing: Macrobenchmark / android-profiler skill on Android, JMH or load tests on JVM.

6. Scalability checklist (new feature or module)

  1. Which layer and module owns each new type? (state the dependency direction)
  2. Does any new dependency break §1/§2?
  3. Is the public surface minimal (internal by default)?
  4. Are fakes for new interfaces added in :core:testing?
  5. Do metrics in §4 still hold for touched files?
  6. Can the feature be removed by deleting its module plus one DI/navigation registration?
  7. Do new files follow §8 (package matches path, file named after its main type, no catch-all Utils, no package past ~15 files)?

7. Bootstrapping quality gates

When the project lacks them, propose (don't silently add) the setup in references/quality-gates.md: Spotless + ktlint, detekt config, Kover, convention plugins, and the GitHub Actions CI template. Ask before adding plugins.

8. Folders, packages and file naming

A large project has hundreds of files, so the path and the name must predict where code lives. Read references/structure-and-naming.md for the full rules. In short:

  • The package mirrors the directory; each module has one root (com.x.feature.login). Group by feature or subdomain first, by role second; never utils, common, managers.
  • A file is named after its main top-level type. Small types that always change together may share a file; independent aggregates (two repositories, two fakes) may not.
  • Suffixes carry the role (*Screen, *ViewModel, *UiState, *UseCase, *Repository, Default*Repository, *DataSource, Fake*, *Test); pick one spelling per project.
  • Tests mirror the source tree. Do not create empty folders ahead of need.
  • Split a package at ~15 files, a file at 500 lines; do moves in their own commit.

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.