---
title: Separate Processing And Data Access
impact: HIGH
impactDescription: enables testable business logic and better maintenance
tags: separation, repository, service, architecture, quality, kotlin
---

## Separate Processing And Data Access

Mixing business logic with raw database queries or data access logic creates tight coupling. This makes testing difficult (requiring a database) and makes the code harder to maintain and refactor.

**Incorrect (mixed concerns):**

```kotlin
class OrderService {
    fun calculateDiscount(userId: String): Double {
        // Business logic mixed with raw SQL or data access
        val user = db.query("SELECT * FROM users WHERE id = ?", userId)
        val orders = db.query("SELECT * FROM orders WHERE user_id = ?", userId)
        
        var discount = 0.0
        if (orders.size > 10) discount += 0.05
        if (user.getBoolean("isPremium")) discount += 0.10
        
        return discount
    }
}
```

**Correct (separated layers using Repository Pattern):**

```kotlin
// Repository - focus on data mapping and retrieval
interface UserRepository {
    fun findById(userId: String): User?
}

interface OrderRepository {
    fun findByUserId(userId: String): List<Order>
}

// Service - focus on business rules and orchestration
class DiscountService(
    private val userRepository: UserRepository,
    private val orderRepository: OrderRepository
) {
    fun calculateDiscount(userId: String): Double {
        val user = userRepository.findById(userId)
        val orders = orderRepository.findByUserId(userId)
        
        return computeDiscount(user, orders)
    }

    // Business logic is pure and easily testable
    private fun computeDiscount(user: User?, orders: List<Order>): Double {
        var discount = 0.0
        if (orders.size > 10) discount += 0.05
        if (user?.isPremium == true) discount += 0.10
        return discount
    }
}
```

**Benefits:**
- Business logic can be unit-tested without a database.
- Data sources can be swapped (e.g., migrating from SQL to NoSQL) without changing business rules.
- Improved readability and clear separation of concerns.

**Tools:** Architectural Review, Code Review, Manual Audit
