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.
In this repository34 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- android-benchmark-comparisonSkill
- build-and-verifySkill
- compose-animationsSkill
- compose-component-designSkill
- compose-focus-navigationSkill
- compose-performanceSkill
- compose-state-and-effectsSkill
- compose-ui-testing-patternsSkill
- deliver-specSkill
- diagnosing-bugsSkill
- domain-modelingSkill
- gradle-runSkill
- grillingSkill
- grounded-writingSkill
- implement-with-subagentsSkill
- kotlin-api-designSkill
- kotlin-concurrency-and-flowSkill
- kotlin-control-flowSkill
- kotlin-skill-routerSkill
- new-featureSkill
- prototypeSkill
- release-kotlin-librarySkill
- researchSkill
- review-prSkill
- run-github-projectSkill
- run-on-deviceSkill
- setup-environmentSkill
- setup-issue-trackerSkill
- shepherdSkill
- tddSkill
- to-planSkill
- triageSkill
- wayfinderSkill
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
- Distinctive: line 48
Add one when any is true:
- Distinctive: line 58
Don't create a use case per repository method "for consistency".
- Very specific: line 61
Use-case conventions: verb-first name (GetX, ObserveX, PlaceOrder), one public operator fun invoke, suspend for one-shot work and Flow for …
- Very specific: line 70
JVM backend: no UiState/ViewModel. Route/Controller → UseCase (service) → Repository → DataSource.
- Distinctive: line 83
Default module graph (scale down for small projects.
- Very specific: line 101
Prefer implementation over api.
- Distinctive: line 107
Follow Kotlin coding conventions.
- Very specific: line 116
Every @Suppress(...) and every detekt/lint baseline entry carries an inline reason and is named in the report.
- Very specific: line 117
No secrets in source, BuildConfig or committed files.
- Very specific: line 121
Use these as review findings and as detekt/Kover gates.
- Distinctive: line 160
Do metrics in §4 still hold for touched files?
- Very specific: line 162
Do new files follow §8 (package matches path, file named after its main type, no catch-all Utils, no package past ~15 files)?
- Very specific: line 166
When the project lacks them, propose (don't silently add) the setup in references/quality-gates.md: Spotless + ktlint, detekt config, …
≈ “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.
Files
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
| Piece | Layer / module | Owns | Must not |
| UI (composables, screens) | presentation, :feature:x | rendering UiState, forwarding user events as lambdas, UI-only state (scroll, focus, animation, text field drafts) | call repositories/use cases, hold business logic, know DTOs |
| UiState | presentation, :feature:x | an immutable snapshot of everything the screen shows: data class XUiState(...) or a sealed Loading / Content / Error; already formatted for display | contain DTOs/entities, mutable collections, Context, framework types |
| UI event / effect | presentation | one-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:x | exposing StateFlow<UiState>, handling events, mapping domain models/errors → UiState, screen-level coroutine scope | do I/O directly, reference Views/Context/composables, expose MutableStateFlow |
| UseCase (optional) | domain, :core:domain or :feature:x:domain | one business operation: class GetVisibleOrdersUseCase { operator fun invoke(...) }; pure Kotlin, testable without Android | be a pass-through; hold state; depend on data implementations |
| Domain model | domain | entities and value classes with business meaning (OrderId, Money), domain errors (sealed) | carry serialization/DB annotations |
| Repository interface | domain | the contract the app needs (fun observeOrders(): Flow<List<Order>>) | leak where data comes from |
| Repository implementation | data, :core:data | single source of truth, caching/offline policy, merging remote + local, mapping DTO/entity → domain, exception → domain error, dispatcher selection | expose DTOs, be called from UI directly |
| DataSource | data | one source each: OrdersRemoteDataSource (Retrofit/Ktor), OrdersLocalDataSource (Room/SQLDelight/DataStore); DTOs and entities | contain business rules |
When to add a UseCase
Add one when any is true:
- Combines several repositories (e.g. orders + user settings → visible orders).
- Holds a business rule worth testing on its own (validation, pricing, permission checks, sorting/filtering by business meaning).
- Reused by two or more ViewModels (or by ViewModel + background worker/server route).
- Long or multi-step operation that would bloat the ViewModel (checkout: validate → reserve → pay → confirm).
- 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 incommonMainwith 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 akotlin("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
UiStatein the ViewModel (or a small presentation mapper). - Errors: data layer converts exceptions into domain errors (sealed type or
Result); ViewModel maps them to user-facingUiState; presentation never catchesIOException/SQLException. - DI (Hilt/Koin/Metro/Spring) wires implementations at the app/composition root. Domain has no DI annotations other than
@Inject constructorwhere the project already allows it. - Tests per layer: UseCase and repository with fakes (
:core:testing), ViewModel with fake repositories +runTest/Turbine, UI withcompose-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:apimodule or via navigation contracts.:core:*never depends on:feature:*.- Shared build config goes in
build-logicconvention plugins (<proj>.android.library,<proj>.kmp.library,<proj>.jvm.library,<proj>.detekt), not copy-pasted blocks. Versions only ingradle/libs.versions.toml. - Prefer
implementationoverapi; useapionly when a type from the dependency appears in the module's public signatures. - Mark everything
internalby default; public only what other modules use. Library modules useexplicitApi(). - 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
.editorconfigcommitted. - Static analysis: detekt with the project
config/detekt/detekt.yml(template inreferences/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, booleansis/has/should. Folder layout, package roots, file naming and split triggers: §8. - No
!!outside tests; nolateinitfor values that can be constructor parameters; noGlobalScope; no mutable public state (MutableStateFlowexposed publicly). - Immutability first:
val, read-only collections,data classcopies 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,
BuildConfigor 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).
| Metric | Threshold | Tool |
| Cyclomatic complexity per function | ≤ 15 (> 10 is a review smell; detekt has no separate warning level) | detekt CyclomaticComplexMethod |
| Cognitive complexity per function | ≤ 15 | detekt CognitiveComplexMethod |
| Function length | ≤ 60 lines | detekt LongMethod |
| Class length | ≤ 600 lines | detekt LargeClass |
| Parameters | ≤ 6 function / 7 constructor (composables exempt for modifiers/slots) | detekt LongParameterList |
| Nesting depth | ≤ 4 | detekt NestedBlockDepth |
| Functions per class / file | ≤ 20 non-private each (ignorePrivate still counts internal) | detekt TooManyFunctions |
| File length | ≤ 500 lines | review (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 item | Kover koverVerify |
| Module dependency rule | zero violations of §1/§2 | review, ./gradlew :app:dependencies, or a module-graph assertion plugin |
| Public API drift (libraries) | zero unreviewed changes | BCV apiCheck, Kotlin checkKotlinAbi or Metalava |
| Build health | no new compiler warnings; allWarningsAsErrors in CI where feasible | Kotlin compiler |
5. Performance (architecture-level)
- Android startup/runtime: Baseline Profiles (
:baselineprofilemodule), R8 full mode in release (r8-analyzerskill for keep rules), lazy DI for heavy graphs, no disk/network on main thread (StrictMode in debug). - Compose: stable UI state models (immutable,
@Immutable/@Stableonly when true); defer tocompose-performancefor diagnosis. - Coroutines: inject dispatchers (never hard-code
Dispatchers.IOin classes); defer tokotlin-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
exportSchemaon, the exported schema directory committed and aMigrationTestHelpertest; SQLDelight with aschemaOutputDirectory, the committed.dbfiles andverifyMigrationson, soverifySqlDelightMigrationruns incheck.fallbackToDestructiveMigrationin 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-profilerskill on Android, JMH or load tests on JVM.
6. Scalability checklist (new feature or module)
- Which layer and module owns each new type? (state the dependency direction)
- Does any new dependency break §1/§2?
- Is the public surface minimal (
internalby default)? - Are fakes for new interfaces added in
:core:testing? - Do metrics in §4 still hold for touched files?
- Can the feature be removed by deleting its module plus one DI/navigation registration?
- 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; neverutils,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.
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.

