SOLID Principles: Android Examples
Table of Contents
📏 SOLID Principles in Android
SOLID is a set of 5 principles for writing maintainable OOP code.
1. Single Responsibility (SRP)
A class should have one reason to change.
- Bad:
UserActivityhandling UI, Network, and Database. - Good:
UserActivity(UI) ->UserViewModel(State) ->UserRepository(Data) ->UserRemoteSource(Network).
2. Open/Closed (OCP)
Open for extension, closed for modification.
- Bad:
if (type == A) ... else if (type == B) ... - Good: Use interfaces and polymorphism.
interface Payment { fun pay() } class CreditCard : Payment { ... } class PayPal : Payment { ... }
3. Liskov Substitution (LSP)
Subtypes must be substitutable for their base types.
- Bad:
SquareinheritingRectangleand changingsetHeight. - Good: Use composition or separate interfaces.
4. Interface Segregation (ISP)
Clients shouldn’t depend on methods they don’t use.
- Bad:
interface Worker { work(); eat(); }-> Robot doesn’t eat. - Good:
interface Workable { work(); },interface Eatable { eat(); }.
5. Dependency Inversion (DIP)
High-level modules shouldn’t depend on low-level modules. Both should depend on abstractions.
- Bad:
ViewModeldepends onRetrofitUserApidirectly. - Good:
ViewModeldepends onUserRepositoryinterface.UserRepositoryImpldepends onRetrofitUserApi.
🧠 Why It Matters in Android
SOLID prevents “God Activities” and tightly coupled code that breaks when you update libraries (e.g., migrating from Gson to Moshi).
- SRP makes ViewModels testable.
- DIP (via Hilt) allows easy mocking.
- ISP keeps interfaces clean.
🏁 Conclusion
Applying SOLID principles (especially SRP and DIP) is the foundation of Clean Architecture.
You might also be interested in
Clean Architecture: The Ultimate Guide for Modern Android
Demystifying Clean Architecture: A deep dive into layers, dependencies, and data flow to build indestructible Android apps.
Kotlin Delegation: Clean Code Pattern
Master the Delegation pattern in Kotlin. Use `by` keyword to replace inheritance with composition. Practical examples for Android.
MVVM: The View Layer Guide
How to implement the View layer in MVVM with Jetpack Compose. State collection, error handling, and separation of concerns.