<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wiem Yahmed on Medium]]></title>
        <description><![CDATA[Stories by Wiem Yahmed on Medium]]></description>
        <link>https://medium.com/@wiem.yahmed?source=rss-125f6d06f0d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fAfeD00CZHqZgPXO</url>
            <title>Stories by Wiem Yahmed on Medium</title>
            <link>https://medium.com/@wiem.yahmed?source=rss-125f6d06f0d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:22:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wiem.yahmed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SOLID Principles in Android Development: A Beginner’s Guide]]></title>
            <link>https://medium.com/@wiem.yahmed/solid-principles-in-android-development-a-beginners-guide-009c16cff379?source=rss-125f6d06f0d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/009c16cff379</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[andoid-app-development]]></category>
            <dc:creator><![CDATA[Wiem Yahmed]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 11:54:54 GMT</pubDate>
            <atom:updated>2025-01-13T11:54:54.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4nWcnkXFft1SFUGQUm77A.png" /></figure><p>Ever felt overwhelmed by Android app architecture? You’re not alone. In this article, we’ll break down SOLID principles — five powerful guidelines that can transform your Android code from complicated to clean and maintainable. Don’t worry if you’re new to this; we’ll use simple examples anyone can understand.</p><h3>What Are SOLID Principles and Why Should You Care?</h3><p>Imagine building a house of cards. If you place each card carefully and thoughtfully, the structure remains stable. That’s exactly what SOLID principles do for your code — they help you build stable, maintainable Android applications.</p><h3>Let’s Break It Down</h3><h3>S — Single Responsibility Principle (SRP)</h3><p><em>“A class should have only one reason to change”</em></p><p>Think of this like a chef in a kitchen. A chef shouldn’t be washing dishes — that’s the dishwasher’s job. Similarly, in Android:</p><pre>// Bad Example 😟<br>class UserManager {<br>    fun saveUser(user: User) {<br>        // Saves user to database<br>        // Validates user data<br>        // Sends analytics<br>        // Updates UI<br>    }<br>}<br><br>// Good Example 😊<br>class UserRepository {<br>    fun saveUser(user: User) {<br>        // Only handles saving user to database<br>    }<br>}<br><br>class UserValidator {<br>    fun validateUser(user: User): Boolean {<br>        // Only handles user validation<br>    }<br>}</pre><h3>O — Open/Closed Principle</h3><p><em>“Software entities should be open for extension but closed for modification”</em></p><p>Think of this like a smartphone’s case. You can add new features (like a card holder) without changing the phone itself:</p><pre>// Bad Example 😟<br>class PaymentProcessor {<br>    fun processPayment(type: String) {<br>        when (type) {<br>            &quot;credit&quot; -&gt; processCreditCard()<br>            &quot;debit&quot; -&gt; processDebit()<br>            // Adding new payment methods requires modifying this class<br>        }<br>    }<br>}</pre><p>What’s wrong with this code?</p><ol><li>Every time you want to add a new payment method (like cryptocurrency), you need to modify the existing PaymentProcessor class</li><li>The when statement keeps growing</li><li>There’s a risk of breaking existing functionality</li><li>It violates the Single Responsibility Principle too!</li></ol><pre><br>// Good Example 😊<br>interface PaymentMethod {<br>    fun process()<br>}<br><br>class CreditCardPayment : PaymentMethod {<br>    override fun process() {<br>        // Process credit card<br>    }<br>}<br><br>class DebitCardPayment : PaymentMethod {<br>    override fun process() {<br>        // Process debit card<br>    }<br>}</pre><p>Benefits of this approach:</p><ol><li>Adding new payment methods doesn’t require modifying existing code</li><li>Each payment method encapsulates its own logic</li><li>Easy to test each payment method independently</li><li>The PaymentProcessor class doesn’t need to change when adding new payment types</li><li>Reduces the risk of bugs in existing payment methods</li></ol><p>A real-world Android example might look like this:</p><pre>// A more realistic Android implementation<br>interface PaymentMethod {<br>    fun processPayment(amount: Double, onSuccess: () -&gt; Unit, onError: (String) -&gt; Unit)<br>}<br><br>class CreditCardPayment(<br>    private val cardNumber: String,<br>    private val cvv: String,<br>    private val expiryDate: String<br>) : PaymentMethod {<br>    override fun processPayment(<br>        amount: Double,<br>        onSuccess: () -&gt; Unit,<br>        onError: (String) -&gt; Unit<br>    ) {<br>        // Payment processing logic<br>        try {<br>            // Process payment with credit card details<br>            // If successful:<br>            onSuccess()<br>        } catch (e: Exception) {<br>            onError(&quot;Payment failed: ${e.message}&quot;)<br>        }<br>    }<br>}<br><br>// In your Android ViewModel:<br>class PaymentViewModel : ViewModel() {<br>    fun processPayment(paymentMethod: PaymentMethod, amount: Double) {<br>        paymentMethod.processPayment(<br>            amount = amount,<br>            onSuccess = {<br>                // Update UI for success<br>            },<br>            onError = { errorMessage -&gt;<br>                // Update UI for error<br>            }<br>        )<br>    }<br>}</pre><h3>L — Liskov Substitution Principle</h3><p><em>“Objects of a superclass should be replaceable with objects of its subclasses”</em></p><p>Imagine if you could use any TV remote to control basic functions on any TV. That’s LSP in action:</p><p>Let me explain the Liskov Substitution Principle (LSP) in more detail with practical Android examples.</p><p>The LSP states that if you have a class S that is a subclass of class T, then objects of type T in your program should be replaceable with objects of type S without breaking the program’s functionality.</p><p>Let’s break this down with clear examples:</p><pre>// BAD EXAMPLE - Violating LSP<br>open class Rectangle {<br>    open var width: Int = 0<br>    open var height: Int = 0<br>    <br>    open fun setWidth(width: Int) {<br>        this.width = width<br>    }<br>    <br>    open fun setHeight(height: Int) {<br>        this.height = height<br>    }<br>    <br>    fun getArea(): Int = width * height<br>}<br><br>class Square : Rectangle() {<br>    override fun setWidth(width: Int) {<br>        this.width = width<br>        this.height = width  // Square forces width and height to be the same<br>    }<br>    <br>    override fun setHeight(height: Int) {<br>        this.width = height  // This breaks LSP!<br>        this.height = height<br>    }<br>}<br><br>// This code will break for Square:<br>fun calculateAreaForRectangle(rectangle: Rectangle) {<br>    rectangle.setWidth(5)<br>    rectangle.setHeight(4)<br>    // For a Rectangle: area should be 20<br>    // For a Square: area will be 16 (unexpected!)<br>    assert(rectangle.getArea() == 20) // This will fail for Square!<br>}</pre><p>Why is this bad?</p><ol><li>Square changes the expected behavior of Rectangle</li><li>Code that works with Rectangle won’t work correctly with Square</li><li>It violates the “principle of least surprise”</li></ol><p>Here’s a better approach:</p><pre>// GOOD EXAMPLE - Following LSP<br>interface Shape {<br>    fun getArea(): Int<br>}<br><br>class Rectangle(<br>    private var width: Int,<br>    private var height: Int<br>) : Shape {<br>    override fun getArea(): Int = width * height<br>}<br><br>class Square(<br>    private val sideLength: Int<br>) : Shape {<br>    override fun getArea(): Int = sideLength * sideLength<br>}<br><br>// Now this works for all shapes:<br>fun printArea(shape: Shape) {<br>    println(&quot;Area: ${shape.getArea()}&quot;)<br>}</pre><h3>I — Interface Segregation Principle</h3><p><em>“Classes shouldn’t be forced to implement interfaces they don’t use”</em></p><p>Think of this like a restaurant menu. Instead of one huge menu, you have separate menus for food, drinks, and desserts:</p><pre>// Bad Example 😟<br>interface Worker {<br>    fun work()<br>    fun eat()<br>    fun sleep()<br>}<br><br>// Good Example 😊<br>interface Workable {<br>    fun work()<br>}<br><br>interface Eatable {<br>    fun eat()<br>}<br><br>interface Sleepable {<br>    fun sleep()<br>}<br><br>class HumanWorker : Workable, Eatable, Sleepable {<br>    override fun work() { /* ... */ }<br>    override fun eat() { /* ... */ }<br>    override fun sleep() { /* ... */ }<br>}</pre><p>I’ll explain the Interface Segregation Principle (ISP) in detail with practical Android examples.</p><p>The Interface Segregation Principle states that “clients should not be forced to depend on interfaces they don’t use.” In simpler terms: it’s better to have many small, specific interfaces than one large, general interface.</p><p>Let’s look at detailed examples:</p><pre>// BAD EXAMPLE - Violating ISP<br>interface UserActions {<br>    fun login()<br>    fun logout()<br>    fun updateProfile()<br>    fun sendMessage()<br>    fun receiveMessage()<br>    fun uploadPhoto()<br>    fun makePayment()<br>    fun viewHistory()<br>}<br><br>// This class is forced to implement methods it doesn&#39;t need<br>class GuestUser : UserActions {<br>    override fun login() {<br>        // Implementation<br>    }<br>    <br>    override fun logout() {<br>        // Implementation<br>    }<br>    <br>    override fun updateProfile() {<br>        throw NotImplementedException() // Guest can&#39;t update profile!<br>    }<br>    <br>    override fun sendMessage() {<br>        throw NotImplementedException() // Guest can&#39;t send messages!<br>    }<br>    <br>    // ... forced to implement all other methods<br>}</pre><p>Here’s a better approach following ISP:</p><pre>// GOOD EXAMPLE - Following ISP<br><br>// Basic authentication interface<br>interface Authenticatable {<br>    fun login()<br>    fun logout()<br>}<br><br>// Profile management interface<br>interface ProfileManageable {<br>    fun updateProfile()<br>    fun uploadPhoto()<br>}<br><br>// Messaging capabilities interface<br>interface Messageable {<br>    fun sendMessage()<br>    fun receiveMessage()<br>}<br><br>// Payment related interface<br>interface PaymentCapable {<br>    fun makePayment()<br>    fun viewHistory()<br>}<br><br>// Now we can implement only what we need:<br>class GuestUser : Authenticatable {<br>    override fun login() {<br>        // Implementation<br>    }<br>    <br>    override fun logout() {<br>        // Implementation<br>    }<br>}<br><br>class RegularUser : Authenticatable, ProfileManageable, Messageable {<br>    override fun login() { /* ... */ }<br>    override fun logout() { /* ... */ }<br>    override fun updateProfile() { /* ... */ }<br>    override fun uploadPhoto() { /* ... */ }<br>    override fun sendMessage() { /* ... */ }<br>    override fun receiveMessage() { /* ... */ }<br>}<br><br>class PremiumUser : Authenticatable, ProfileManageable, Messageable, PaymentCapable {<br>    // Implements all methods...<br>}</pre><h3>D — Dependency Inversion Principle</h3><p>“High-level modules shouldn’t depend on low-level modules. Both should depend on abstractions”</p><p>Think of this like plugging devices into a power outlet. You don’t need to know how electricity works; you just need to know the interface (the outlet):</p><pre>// Bad Example 😟<br>class UserRepository {<br>    private val database = SQLiteDatabase() // Direct dependency<br>    <br>    fun getUser(id: String): User {<br>        return database.query(id)<br>    }<br>}<br><br>// Good Example 😊<br>interface Database {<br>    fun query(id: String): User<br>}<br><br>class SQLiteDatabase : Database {<br>    override fun query(id: String): User {<br>        // Implementation<br>    }<br>}<br><br>class UserRepository(private val database: Database) {<br>    fun getUser(id: String): User {<br>        return database.query(id)<br>    }<br>}</pre><p>I’ll explain the Dependency Inversion Principle (DIP) in more detail with practical Android examples.</p><p>The principle states that:</p><ol><li>High-level modules should not depend on low-level modules. Both should depend on abstractions.</li><li>Abstractions should not depend on details. Details should depend on abstractions.</li></ol><p>Let’s break this down with detailed examples:</p><pre>// BAD EXAMPLE - Violating DIP<br>class UserRepository {<br>    // Direct dependency on concrete SQLite implementation<br>    private val database = SQLiteDatabase.getInstance()<br>    <br>    fun saveUser(user: User) {<br>        // Directly using SQLite<br>        database.execSQL(&quot;INSERT INTO users (name, email) VALUES (?, ?)&quot;, <br>            arrayOf(user.name, user.email))<br>    }<br>    <br>    fun getUser(id: String): User {<br>        val cursor = database.rawQuery(&quot;SELECT * FROM users WHERE id = ?&quot;, <br>            arrayOf(id))<br>        // Parse cursor and return user<br>        return User(cursor)<br>    }<br>}<br><br>// Usage in ViewModel<br>class UserViewModel {<br>    // Direct dependency on concrete implementation<br>    private val repository = UserRepository()<br>    <br>    fun saveUser(user: User) {<br>        repository.saveUser(user)<br>    }<br>}</pre><p>Here’s a better approach following DIP:</p><pre>// GOOD EXAMPLE - Following DIP<br><br>// Abstractions (interfaces)<br>interface DatabaseService {<br>    fun saveUser(user: User)<br>    fun getUser(id: String): User<br>    fun deleteUser(id: String)<br>    fun updateUser(user: User)<br>}<br><br>interface UserDataSource {<br>    suspend fun saveUser(user: User): Result&lt;Unit&gt;<br>    suspend fun getUser(id: String): Result&lt;User&gt;<br>    suspend fun deleteUser(id: String): Result&lt;Unit&gt;<br>    suspend fun updateUser(user: User): Result&lt;Unit&gt;<br>}<br><br>// Low-level implementation details<br>class SQLiteDataSource(<br>    private val database: SQLiteDatabase<br>) : DatabaseService {<br>    override fun saveUser(user: User) {<br>        database.execSQL(<br>            &quot;INSERT INTO users (name, email) VALUES (?, ?)&quot;, <br>            arrayOf(user.name, user.email)<br>        )<br>    }<br>    <br>    override fun getUser(id: String): User {<br>        val cursor = database.rawQuery(<br>            &quot;SELECT * FROM users WHERE id = ?&quot;, <br>            arrayOf(id)<br>        )<br>        return User(cursor)<br>    }<br>    <br>    override fun deleteUser(id: String) {<br>        database.execSQL(&quot;DELETE FROM users WHERE id = ?&quot;, arrayOf(id))<br>    }<br>    <br>    override fun updateUser(user: User) {<br>        database.execSQL(<br>            &quot;UPDATE users SET name = ?, email = ? WHERE id = ?&quot;,<br>            arrayOf(user.name, user.email, user.id)<br>        )<br>    }<br>}<br><br>class RoomDataSource(<br>    private val userDao: UserDao<br>) : DatabaseService {<br>    override fun saveUser(user: User) {<br>        userDao.insert(user)<br>    }<br>    <br>    override fun getUser(id: String): User {<br>        return userDao.getUser(id)<br>    }<br>    <br>    override fun deleteUser(id: String) {<br>        userDao.delete(id)<br>    }<br>    <br>    override fun updateUser(user: User) {<br>        userDao.update(user)<br>    }<br>}<br><br>// Repository depends on abstraction, not concrete implementation<br>class UserRepository(<br>    private val databaseService: DatabaseService<br>) : UserDataSource {<br>    override suspend fun saveUser(user: User): Result&lt;Unit&gt; {<br>        return try {<br>            databaseService.saveUser(user)<br>            Result.success(Unit)<br>        } catch (e: Exception) {<br>            Result.failure(e)<br>        }<br>    }<br>    <br>    override suspend fun getUser(id: String): Result&lt;User&gt; {<br>        return try {<br>            val user = databaseService.getUser(id)<br>            Result.success(user)<br>        } catch (e: Exception) {<br>            Result.failure(e)<br>        }<br>    }<br>    <br>    // Other implementations...<br>}<br><br>// ViewModel depends on abstraction<br>class UserViewModel(<br>    private val userDataSource: UserDataSource<br>) : ViewModel() {<br>    <br>    private val _userState = MutableLiveData&lt;Result&lt;User&gt;&gt;()<br>    val userState: LiveData&lt;Result&lt;User&gt;&gt; = _userState<br>    <br>    fun loadUser(id: String) {<br>        viewModelScope.launch {<br>            _userState.value = userDataSource.getUser(id)<br>        }<br>    }<br>    <br>    fun saveUser(user: User) {<br>        viewModelScope.launch {<br>            val result = userDataSource.saveUser(user)<br>            // Handle result<br>        }<br>    }<br>}</pre><p>A practical example with dependency injection using Hilt:</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>object DatabaseModule {<br>    <br>    @Provides<br>    @Singleton<br>    fun provideDatabaseService(<br>        @ApplicationContext context: Context<br>    ): DatabaseService {<br>        // You can easily switch implementations here<br>        return SQLiteDataSource(SQLiteDatabase.getInstance(context))<br>        // Or return RoomDataSource(database.userDao())<br>    }<br>    <br>    @Provides<br>    @Singleton<br>    fun provideUserDataSource(<br>        databaseService: DatabaseService<br>    ): UserDataSource {<br>        return UserRepository(databaseService)<br>    }<br>}<br><br>@HiltViewModel<br>class UserViewModel @Inject constructor(<br>    private val userDataSource: UserDataSource<br>) : ViewModel() {<br>    // Implementation remains the same<br>}</pre><p>Usage in an Activity or Fragment:</p><pre>@AndroidEntryPoint<br>class UserProfileActivity : AppCompatActivity() {<br>    <br>    private val viewModel: UserViewModel by viewModels()<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        <br>        viewModel.userState.observe(this) { result -&gt;<br>            result.fold(<br>                onSuccess = { user -&gt;<br>                    // Update UI with user data<br>                    updateUI(user)<br>                },<br>                onFailure = { error -&gt;<br>                    // Handle error<br>                    showError(error)<br>                }<br>            )<br>        }<br>    }<br>}</pre><h3>Putting It All Together</h3><p>When you apply these principles in your Android development:</p><ul><li>Your code becomes easier to test</li><li>New features become easier to add</li><li>Bugs become easier to fix</li><li>Team collaboration becomes smoother</li></ul><h3>Real-World Impact</h3><p>Let’s look at a practical example. Here’s how these principles might work together in a simple note-taking app feature:</p><pre>// Using all SOLID principles<br>interface NoteRepository {<br>    fun saveNote(note: Note)<br>    fun getNote(id: String): Note<br>}<br><br>interface NoteValidator {<br>    fun validateNote(note: Note): Boolean<br>}<br><br>class NoteManager(<br>    private val repository: NoteRepository,<br>    private val validator: NoteValidator<br>) {<br>    fun createNote(note: Note): Boolean {<br>        return if (validator.validateNote(note)) {<br>            repository.saveNote(note)<br>            true<br>        } else {<br>            false<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>SOLID principles might seem abstract at first, but they’re like training wheels for writing better code. Start applying them one at a time, and you’ll see your Android applications become more maintainable, flexible, and robust.</p><p>Remember:</p><ul><li>Single Responsibility: One job per class</li><li>Open/Closed: Easy to extend, hard to break</li><li>Liskov Substitution: Subtypes should work like their parent types</li><li>Interface Segregation: Small, specific interfaces are better than large, general ones</li><li>Dependency Inversion: Depend on abstractions, not concrete implementations</li></ul><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=009c16cff379" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>