---
title: Không đặt logic nghiệp vụ trong init
impact: MEDIUM
impactDescription: Logic phức tạp trong init làm khó test, gây side-effect không mong muốn và vi phạm nguyên tắc Single Responsibility.
tags: swift, ios, init, constructor, architecture, code-quality
---

## Không đặt logic nghiệp vụ trong init

`init` chỉ nên gán giá trị cho các property. Đừng gọi API, đọc file, khởi động timer, hay thực hiện tính toán phức tạp bên trong `init`. Nếu cần, tách ra thành hàm `configure()` hoặc `setup()` gọi sau khi khởi tạo.

**Incorrect (logic trong init):**

```swift
class UserProfileViewModel {
    var user: User?
    var recentOrders: [Order] = []

    init(userId: String) {
        // Gọi API trong init - không thể control được
        let user = UserAPIService.shared.fetchUserSync(userId: userId)
        self.user = user

        // Logic nghiệp vụ trong init
        if let user = user, user.isPremium {
            recentOrders = OrderAPIService.shared.fetchOrdersSync(userId: userId)
        }

        // Đọc file trong init
        let config = try? JSONDecoder().decode(Config.self, from: Data(contentsOf: configURL))
    }
}
```

**Correct (init đơn giản + hàm setup riêng):**

```swift
class UserProfileViewModel {
    private let userId: String
    private let apiService: UserAPIServiceProtocol

    var user: User?
    var recentOrders: [Order] = []

    init(userId: String, apiService: UserAPIServiceProtocol) {
        self.userId = userId
        self.apiService = apiService
        // Không có logic nghiệp vụ ở đây
    }

    // Gọi sau khi khởi tạo - dễ test, dễ control
    func loadData() async {
        do {
            user = try await apiService.fetchUser(userId: userId)
            if user?.isPremium == true {
                recentOrders = try await apiService.fetchOrders(userId: userId)
            }
        } catch {
            // xử lý lỗi
        }
    }
}
```

**Tools:** Code Review, SwiftLint custom rule

