---
title: Centralize Constants
impact: HIGH
impactDescription: makes values easy to find, update, and understand
tags: constants, magic-numbers, configuration, quality, kotlin
---

## Centralize Constants

Magic numbers or strings scattered throughout the code are difficult to manage and prone to errors. Centralizing constants makes the codebase more maintainable and self-documenting.

**Incorrect (magic numbers and strings):**

```kotlin
if (password.length < 8) { }
if (retryCount > 3) { }
if (status == 1) { }
Handler().postDelayed(callback, 300000)
if (user.role == "admin") { }
```

**Correct (centralized constants):**

```kotlin
// Constants.kt or within an object
object Config {
    const val PASSWORD_MIN_LENGTH = 8
    const val MAX_RETRY_ATTEMPTS = 3
    const val SESSION_TIMEOUT_MS = 5 * 60 * 1000L // 5 minutes
}

enum class OrderStatus(val value: Int) {
    PENDING(1),
    APPROVED(2),
    SHIPPED(3)
}

object UserRoles {
    const val ADMIN = "admin"
    const val USER = "user"
    const val GUEST = "guest"
}

// Usage
if (password.length < Config.PASSWORD_MIN_LENGTH) { }
if (retryCount > Config.MAX_RETRY_ATTEMPTS) { }
if (status == OrderStatus.PENDING.value) { }
Handler().postDelayed(callback, Config.SESSION_TIMEOUT_MS)
if (user.role == UserRoles.ADMIN) { }
```

**Benefits:**
- Single source of truth.
- Improved readability and domain expression.
- Avoids duplication and "search-and-replace" errors.
- Type safety (especially when using Enums or Sealed Classes).

**Tools:** detekt (MagicNumber), Android Studio Linter, Manual Review
