Refactor (Android Architecture Aligned)
Refactor existing code to align with the official Android architecture. No external behavior changes.
Principles
- •No behavior changes: Refactoring improves internal structure only
- •Incremental steps: Avoid large changes at once
- •Build verification at each step: Revert immediately if broken
Refactoring Patterns
Layer Separation (Highest Priority)
When business logic exists in Activity/Fragment:
- •Extract UI State as a
data class - •Create a ViewModel and move logic into it
- •Expose state via
StateFlow<UiState> - •UI collects with
collectAsStateWithLifecycle() - •Define user actions as
sealed interface
Introducing Repository Pattern:
- •Extract data access into a Repository interface
- •Create implementation class (inject DataSource)
- •ViewModel depends only on Repository
ViewModel Improvements
- •Consolidate multiple
MutableState→ singleUiStatedata class - •Migrate
LiveData→StateFlow - •Apply
stateIn(SharingStarted.WhileSubscribed(5_000)) - •Convert one-off events to state (event → state pattern)
Compose Improvements
- •Split large Composables (one Composable ≈ one responsibility)
- •Apply state hoisting (make Composables stateless)
- •Optimize with
remember/derivedStateOf - •Add
@Previewfunctions - •Replace
NavControllerpassing with callback pattern
DI Introduction/Improvement
- •Migrate Manual DI → Hilt
- •
@HiltViewModel+@Inject constructor - •Use
@Bindsfor interface bindings - •Optimize scopes
Kotlin Idioms
- •Use
whenexpressions - •Convert to
sealed class/sealed interface - •Leverage extension functions
- •Remove unnecessary !! (use
?.let,requireNotNull, defaults) - •Use
data classappropriately
Build Configuration Improvements
- •Consolidate into Version Catalog (
libs.versions.toml) - •Introduce Convention Plugins (for multi-module projects)
- •Remove unused dependencies
Procedure
Step 1: Current State Analysis
- •List issues in the target code
- •Create a refactoring plan (tracked with TodoWrite)
Step 2: Incremental Execution
- •Execute one step at a time following the plan
- •After each step:
./gradlew assembleDebug
Step 3: Final Verification
bash
./gradlew assembleDebug ./gradlew test ./gradlew lint
Step 4: Change Summary
Report before/after architecture comparison and improvements made.
Target
$ARGUMENTS