Paperless / rebuild
Course 2 28ef273

java-style.md

docs/java-style.md

Snapshot 28ef273Download original
1# Kotlin Style & Formatting23> [!NOTE]4> The project backend uses Kotlin. This guide defines the Kotlin coding and formatting standards. See also [`docs/kotlin-style.md`](kotlin-style.md).56## Formatting Rules78- **Indentation:** 4 spaces (no tabs).9- **Line length:** 120 characters maximum.10- **Code style:** Official Kotlin Coding Conventions / IntelliJ IDEA default Kotlin style.11- **Encoding:** UTF-8.12- **Blank lines:** Blank lines separate logical blocks. Always put a blank line before and after a `return` statement, a `when` expression, a loop (`for`, `while`), or a multiline chained call sequence — unless it is the first or last line in its enclosing block.1314## Automated Enforcement1516Do not rely on manual formatting review:17- Enforce formatting using **Spotless** (with ktlint) or **ktlint**:18  - Fix formatting:19    ```bash20    ./gradlew spotlessApply21    ```22  - Verify formatting in CI and pre-commit/pre-push quality gates:23    ```bash24    ./gradlew spotlessCheck25    ```2627## Variables & Immutability (`val` vs. `var`)2829- **Prefer `val` over `var` everywhere:**30  - Function parameters in Kotlin are implicitly `val` (immutable by definition).31  - Use `val` for all local variables, properties, and references by default.32  - Use `var` only when local mutable state is strictly necessary and cannot be cleanly expressed with immutability.33- **Type inference vs. explicit types:**34  - Use type inference (`val task = ...`) for local variables in **controllers** and **tests**, and where the type is obvious from the right-hand side expression.35  - Declare **explicit return types** on all `public` and `protected` functions in **services**, **repositories**, and **mappers** to ensure clear API contracts:36    ```kotlin37    fun searchTasks(pageable: Pageable): Page<Task>38    ```3940## Null Safety & Idiomatic Checks4142- Leverage Kotlin's type system (`String` vs. `String?`) — avoid nullable types unless nullability is a legitimate domain state.43- **Never use `!!` (not-null assertion):** Handle missing values gracefully or fail with a domain exception:44  ```kotlin45  val task = taskRepository.findByIdOrNull(id)46      ?: throw AppException(AppErrorMessage.TASK_NOT_FOUND)47  ```48- Use standard library null/blank checks:49  - `isNullOrEmpty()` and `isNullOrBlank()` on strings and collections.50  - `checkNotNull(...)` or `requireNotNull(...)` when enforcing internal invariants.5152## Data Classes & Constructors5354- **Parameter count:** Maximum 3 parameters on functions or constructors. If more related parameters are needed, group them into a Kotlin `data class`.55- **Data classes for models and DTOs:** Use `data class` with `val` properties for immutable models, DTOs, and value objects.56- **No builders needed:** Kotlin supports default argument values and named arguments. Do not use builder patterns or `@Builder`:57  ```kotlin58  val task = Task(59      id = dto.id,60      title = dto.title,61      status = TaskStatus.OPEN62  )63  ```64- Declare dependencies in the primary constructor in the class header:65  ```kotlin66  @Service67  @Transactional68  class TaskServiceImpl(69      private val taskRepository: TaskRepository,70      private val userClient: UserClient71  ) : TaskService { ... }72  ```7374## Language Idioms & Control Flow7576- **Expression bodies:** Use single-expression syntax (`fun calculate() = ...`) when a function consists of a single concise expression.77- **`when` expressions:** Prefer `when` expressions over chained `if` / `else if` / `else` or Java-style switches:78  ```kotlin79  val status = when (input) {80      "ACTIVE" -> Status.ACTIVE81      "INACTIVE" -> Status.INACTIVE82      else -> throw AppException(AppErrorMessage.INVALID_STATUS)83  }84  ```85- **Control flow:** Prefer early returns with guard clauses (`?: return ...`, `?: throw ...`) over deeply nested branches.86- **Collections:**87  - Prefer read-only collection interfaces (`List`, `Set`, `Map`) over mutable collections (`MutableList`).88  - Use idiomatic functional operations (`map`, `filter`, `associate`, `flatMap`, `firstOrNull`) rather than imperative loops.89- **Named conditions:** Wrap compound boolean conditions in a descriptive named `val` rather than inlining complex expressions.9091## Constants & No Magic Values9293- Replace magic numbers and strings with named constants.94- Define constants as `const val` within a `companion object` or as top-level private `const val` in the relevant file:95  ```kotlin96  companion object {97      private const val MAX_RETRY_ATTEMPTS = 398  }99  ```100101## Exceptions102103- Kotlin does not have checked exceptions. Do not use `@Throws` except for specific Java interop requirements.104- Throw unchecked domain exceptions (`throw AppException(AppErrorMessage.<X>)`).105106## Comments & Documentation107108- Omit comments on obvious or self-explanatory code.109- Reserve comments for cron expressions, non-trivial regex patterns, `TODO` markers, or `// given` / `// when` / `// then` test structure separators.110- Skip KDoc on obvious classes and methods.111112## Annotations & Overrides113114- The `override` keyword is compiler-enforced; always mark overridden interface or superclass methods with `override`.115- Ensure annotation targets are explicit when needed (e.g. `@field:Valid` on data class properties when Bean Validation requires field targeting).116117## Imports118119- No wildcard imports (`import foo.bar.*` is forbidden).120

Search chapters, reference and source filenames.