Clean Architecture
Semua project mobile di Bit Group Asia wajib mengikuti prinsip Clean Architecture untuk memastikan separation of concerns, testability, dan maintainability.
Prinsip Utama
- Independence of Frameworks — Arsitektur tidak bergantung pada framework tertentu.
- Testable — Business logic dapat ditest tanpa UI, database, atau API.
- Independence of UI — UI dapat berubah tanpa mengubah business logic.
- Independence of Database — Database dapat diganti tanpa mengubah business logic.
Layer Structure
Dependency Rule
Dependencies hanya boleh mengarah ke dalam (dari luar ke dalam).
- Presentation → boleh depend ke Domain
- Data → boleh depend ke Domain
- Domain → TIDAK BOLEH depend ke Presentation atau Data
Clean Architecture ≠ Struktur Folder
Clean Architecture mengatur arah dependensi dan pemisahan tanggung jawab, bukan bentuk folder. Layer di atas tetap ada di semua platform, tapi letaknya mengikuti struktur terbaik masing-masing platform (feature-first). Lihat Folder Structure.
| Platform | Data | Domain | Presentation |
|---|---|---|---|
| Android | :core:data, :core:network, :core:database | :core:domain, :core:model | :feature:* |
| iOS | AppData, AppNetworking, AppPersistence | AppDomain | *Feature |
| Flutter | features/x/data/ | features/x/domain/ | features/x/presentation/ |
| React Native | features/x/api/ | features/x/types.ts, features/x/logic/ | features/x/screens/, components/ |
Use Case Opsional
Use case wajib hanya kalau ada logic bisnis, penggabungan lebih dari satu repository, atau logic yang dipakai ulang oleh beberapa ViewModel. Untuk operasi sederhana, ViewModel / Cubit boleh langsung memakai interface repository (garis putus-putus di diagram). Dependency Rule tetap terpenuhi karena yang dipakai adalah kontrak di domain, bukan implementasinya.
Varian Pragmatis React Native
React Native tetap memisahkan data, domain, dan presentation, tapi tanpa class UseCase / RepositoryImpl dan tanpa interface repository: hook TanStack Query memanggil fungsi API secara langsung. Ini kompromi yang disengaja, karena TanStack Query sudah menangani cache dan sinkronisasi, dan pola class terasa berat di React. Konsekuensinya, test mengganti HTTP-nya (MSW / jest.mock pada module API), bukan repository.
Implementasi per Platform
- Android (Kotlin)
- iOS (Swift)
- Flutter (Dart)
- React Native (TS)
// Domain Layer - Use Case
class GetUserUseCase(
private val repository: UserRepository // Interface
) {
suspend operator fun invoke(id: String): Result<User> {
return repository.getUser(id)
}
}
// Domain Layer - Repository Interface
interface UserRepository {
suspend fun getUser(id: String): Result<User>
}
// Data Layer - Repository Implementation
class UserRepositoryImpl(
private val api: UserApiService,
private val dao: UserDao,
) : UserRepository {
override suspend fun getUser(id: String): Result<User> {
val result = safeCall {
val dto = api.getUser(id)
dao.insertUser(dto.toEntity())
dto.toDomain()
}
// Fallback ke cache hanya untuk masalah koneksi,
// bukan untuk 401 / validasi / error server.
val error = result.exceptionOrNull()
if (error == AppError.Network || error == AppError.Timeout) {
dao.getUser(id)?.let { return Result.success(it.toDomain()) }
}
return result
}
}
catch (e: Exception) di suspend functionCancellationException adalah turunan Exception. Menangkapnya tanpa melempar ulang membuat coroutine yang seharusnya dibatalkan (misalnya user keluar dari screen) tetap jalan dan bisa meng-update state yang sudah tidak dipakai. Hal yang sama berlaku untuk runCatching { } di suspend function. Pakai safeCall di Error Handling → Android, yang selalu melempar ulang CancellationException.
// Domain Layer - Use Case
struct GetUserUseCase: Sendable {
let repository: UserRepositoryProtocol
func execute(id: String) async throws -> User {
try await repository.getUser(id: id)
}
}
// Domain Layer - Repository Protocol
protocol UserRepositoryProtocol: Sendable {
func getUser(id: String) async throws -> User
}
// Data Layer - Repository Implementation
final class UserRepository: UserRepositoryProtocol {
private let apiService: UserAPIServiceProtocol // protocol: Sendable
private let localStore: UserLocalStoreProtocol // protocol: Sendable
init(apiService: UserAPIServiceProtocol, localStore: UserLocalStoreProtocol) {
self.apiService = apiService
self.localStore = localStore
}
func getUser(id: String) async throws -> User {
do {
let dto = try await apiService.getUser(id: id)
try await localStore.save(dto.toEntity())
return dto.toDomain()
} catch let error where error.isCancellation {
throw error // jangan diubah jadi AppError
} catch {
let appError = AppError(error)
// Fallback ke cache hanya untuk masalah koneksi
if appError == .network || appError == .timeout,
let cached = try? await localStore.getUser(id: id) {
return cached.toDomain()
}
throw appError
}
}
}
AppError dan isCancellation dijelaskan di Error Handling → iOS.
// Domain Layer - Use Case
class GetUserUseCase {
GetUserUseCase(this._repository);
final UserRepository _repository;
Future<Result<User>> call(String id) => _repository.getUser(id);
}
// Domain Layer - Repository Interface
abstract interface class UserRepository {
Future<Result<User>> getUser(String id);
}
// Data Layer - Repository Implementation
class UserRepositoryImpl implements UserRepository {
UserRepositoryImpl(this._remote, this._local);
final UserRemoteDataSource _remote;
final UserLocalDataSource _local;
Future<Result<User>> getUser(String id) async {
final result = await guard(() async {
final dto = await _remote.getUser(id);
await _local.cacheUser(dto);
return dto.toEntity();
});
// Fallback ke cache hanya untuk masalah koneksi,
// bukan untuk 401 / validasi / error server.
if (result case Err(failure: NetworkFailure() || TimeoutFailure())) {
final cached = await _local.getUser(id);
if (cached != null) return Ok(cached.toEntity());
}
return result;
}
}
Result, Failure, dan guard() dijelaskan di Error Handling → Implementasi Flutter. Struktur folder per fitur ada di Flutter → Project Structure.
Di React Native, layer diwujudkan sebagai file dan fungsi, bukan class. Peran repository + cache diambil alih TanStack Query. Lihat RN CLI → Project Structure.
// features/user/types.ts — Domain model
export interface User {
id: string;
name: string;
joinedAt: Date;
}
// features/user/logic/isProbation.ts — Aturan bisnis (fungsi murni, mudah ditest)
export function isProbation(user: User, now = new Date()): boolean {
const threeMonths = 1000 * 60 * 60 * 24 * 90;
return now.getTime() - user.joinedAt.getTime() < threeMonths;
}
// features/user/api/user.api.ts — Data layer: request + validasi + mapping
const userDtoSchema = z.object({
id: z.string(),
full_name: z.string(),
joined_at: z.string(),
});
export async function getUser(id: string): Promise<User> {
const { data } = await apiClient.get(`/users/${id}`);
const dto = userDtoSchema.parse(data);
return { id: dto.id, name: dto.full_name, joinedAt: new Date(dto.joined_at) };
}
// features/user/api/useUser.ts — Server state (cache, retry, offline) via TanStack Query
export function useUser(id: string) {
return useQuery({ queryKey: ['users', id], queryFn: () => getUser(id) });
}
Setiap layer memiliki model sendiri:
- DTO (Data Transfer Object) — untuk komunikasi API
- Entity — untuk penyimpanan lokal
- Domain Model — untuk business logic dan presentation
Gunakan mapper/extension function untuk konversi antar model.
Di Flutter, istilah Entity dipakai untuk domain model (domain/entities/), sedangkan model penyimpanan lokal diberi nama sesuai tool-nya (misalnya tabel Drift UserTable). Lihat tabel naming Flutter.