---
title: Không để logic parsing/mapping trong ViewController
impact: HIGH
impactDescription: Logic phân tích dữ liệu trong ViewController làm phình to class, khó test và vi phạm Single Responsibility Principle.
tags: swift, ios, mvc, mvvm, viewcontroller, parsing, architecture
---

## Không để logic parsing/mapping trong ViewController

ViewController chỉ nên lo presentation: bind data lên UI, xử lý user interaction. Logic parse JSON, map model sang ViewModel, validate, hay transform dữ liệu phải nằm trong tầng riêng (ViewModel, Mapper, UseCase).

**Incorrect (parsing/mapping trong ViewController):**

```swift
class OrderListViewController: UIViewController {

    // !! Logic mapping trong VC
    func configureCell(_ cell: OrderCell, with orderData: [String: Any]) {
        let id = orderData["id"] as? String ?? ""
        let status = orderData["status"] as? String ?? "unknown"
        let amount = orderData["total_amount"] as? Double ?? 0.0
        let dateString = orderData["created_at"] as? String ?? ""

        // Date parsing trực tiếp trong VC
        let formatter = ISO8601DateFormatter()
        let date = formatter.date(from: dateString) ?? Date()
        let displayDate = DateFormatter.medium.string(from: date)

        cell.orderIdLabel.text = "#\(id)"
        cell.statusLabel.text = status.capitalized
        cell.amountLabel.text = "$\(String(format: "%.2f", amount))"
        cell.dateLabel.text = displayDate
    }
}
```

**Correct (VC chỉ bind, ViewModel lo mapping):**

```swift
// OrderViewModel - lo mapping và formatting
struct OrderViewModel {
    let displayId: String
    let statusText: String
    let formattedAmount: String
    let displayDate: String

    init(order: Order) {
        self.displayId = "#\(order.id)"
        self.statusText = order.status.localizedTitle
        self.formattedAmount = NumberFormatter.currency.string(from: NSNumber(value: order.totalAmount)) ?? ""
        self.displayDate = DateFormatter.medium.string(from: order.createdAt)
    }
}

// ViewController - chỉ bind data lên UI
class OrderListViewController: UIViewController {
    func configureCell(_ cell: OrderCell, with viewModel: OrderViewModel) {
        cell.orderIdLabel.text = viewModel.displayId
        cell.statusLabel.text = viewModel.statusText
        cell.amountLabel.text = viewModel.formattedAmount
        cell.dateLabel.text = viewModel.displayDate
    }
}
```

**Tools:** Code Review, Unit Tests (ViewModel test không cần UIKit)

