Мое фото | My photo

Почему BLoC актуален, а чистая архитектура устаревает | Why BLoC matters while clean architecture fades

← Назад к статьям | Back to articles

Введение

В мире Android-разработки идут постоянные споры о выборе архитектуры. Чистая архитектура (Clean Architecture), предложенная Робертом Мартином, долгое время считалась золотым стандартом. Однако современные реалии и появление таких подходов как BLoC (Business Logic Component) заставляют пересмотреть устоявшиеся догмы.

Проблемы чистой архитектуры

Основная идея чистой архитектуры - изоляция бизнес-логики от платформы - на практике оказывается избыточной. В реальных проектах переиспользование бизнес-логики между разными платформами происходит крайне редко, а если и происходит, то требует специальных технологий вроде Kotlin Multiplatform.

Традиционное разделение на data/domain/presentation слои приводит к:

Преимущества BLoC подхода

BLoC предлагает альтернативу, основанную на:

  1. Компонентности - вместо слоёв появляются независимые компоненты бизнес-логики
  2. Композиции - вместо наследования и сложных иерархий
  3. Инкапсуляции - чёткие границы через State/Event модель
  4. Реактивности - естественная работа с потоками данных

Практические сравнения

Рассмотрим реализацию функции аутентификации в обоих подходах:

Чистая архитектура:

// Domain
interface AuthRepository
class AuthUseCase(repo: AuthRepository)

// Data
class AuthRepositoryImpl: AuthRepository

// Presentation
class AuthViewModel(useCase: AuthUseCase)

BLoC подход:

class AuthBloc(authService: AuthService) {
    private val _state = MutableStateFlow<AuthState>(Idle)
    val state: StateFlow<AuthState> = _state.asStateFlow()

    fun sendEvent(event: AuthEvent) { ... }
}

BLoC версия более компактна и содержит всю логику в одном месте, сохраняя при этом тестируемость.

Когда Clean Architecture ещё актуальна?

Чистая архитектура сохраняет ценность в:

———

Introduction

In the world of Android development, there are constant debates about architecture choice. Clean Architecture, proposed by Robert Martin, was long considered the gold standard. However, modern realities and the emergence of approaches like BLoC (Business Logic Component) force us to reconsider established dogmas.

Problems of Clean Architecture

The main idea of Clean Architecture - isolating business logic from the platform - proves excessive in practice. In real projects, reuse of business logic between different platforms is extremely rare, and when it does happen, it requires special technologies like Kotlin Multiplatform.

The traditional separation into data/domain/presentation layers leads to:

Advantages of BLoC Approach

BLoC offers an alternative based on:

  1. Component-based design - instead of layers, we get independent business logic components
  2. Composition - instead of inheritance and complex hierarchies
  3. Encapsulation - clear boundaries through State/Event model
  4. Reactivity - natural work with data streams

Practical Comparisons

Let's examine the implementation of authentication feature in both approaches:

Clean Architecture:

// Domain
interface AuthRepository
class AuthUseCase(repo: AuthRepository)

// Data
class AuthRepositoryImpl: AuthRepository

// Presentation
class AuthViewModel(useCase: AuthUseCase)

BLoC Approach:

class AuthBloc(authService: AuthService) {
    private val _state = MutableStateFlow<AuthState>(Idle)
    val state: StateFlow<AuthState> = _state.asStateFlow()

    fun sendEvent(event: AuthEvent) { ... }
}

The BLoC version is more compact and contains all logic in one place while maintaining testability.

When is Clean Architecture Still Relevant?

Clean Architecture retains value in:

Заключение | Conclusion

BLoC предлагает более современный и прагматичный подход к организации кода в Android-разработке. Он сохраняет ключевые преимущества чистой архитектуры (тестируемость, разделение ответственности), но без избыточного усложнения. Для большинства современных мобильных проектов BLoC оказывается более подходящим выбором.

BLoC offers a more modern and pragmatic approach to code organization in Android development. It preserves the key advantages of clean architecture (testability, separation of concerns) but without excessive complexity. For most modern mobile projects, BLoC proves to be a more suitable choice.