---
title: Tránh khởi tạo trực tiếp các system types
impact: MEDIUM
impactDescription: Tránh việc tạo các instance không hợp lệ hoặc không cần thiết của các system types có sẵn cơ chế factory/singleton.
tags: swift, ios, bundle, uidevice, initialization
---

## Tránh khởi tạo trực tiếp các system types

Tránh khởi tạo trực tiếp các kiểu như: `Bundle`, `NSError`, `UIDevice`. Sử dụng các factory method hoặc properties sẵn có (như `.main`, `.current`) thay vì gọi `init()` trực tiếp để đảm bảo tính nhất quán và hiệu năng.

**Incorrect (khởi tạo trực tiếp):**

```swift
let bundle = Bundle()
let device = UIDevice()
let error = NSError()
```

**Correct (sử dụng instance có sẵn):**

```swift
let mainBundle = Bundle.main
let currentDevice = UIDevice.current
let designError = NSError(domain: "com.example", code: 404, userInfo: nil) // Cần truyền tham số nếu tạo mới hợp lệ
```

**Tools:** SwiftLint (discouraged_direct_init)
