This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

SOLID Principles for Android – DEV Community


Solid Principle For android

As a developer, there comes a time when we’ve got be taught rules to maneuver forward in profession. For some this subject is likely to be new, for some they’re already skilled on these rules.
Let’s Start,
Each letter in SOLID , represents one precept.

The Fist Precept that we’ll discuss

S – Single Accountability Precept ( SRP )

This one is simple to grasp, nevertheless it may take you a while to get in reminiscence muscle.

Actual world Instance – As an instance you’re a chef in a restaurant, now you ought to be chargeable for making the meals proper.
Now in case you given additionally the duty of dealing with the staffs in kitchen or serving meals, will make the work difficult proper.

That is how in programming, a way that you’ve declared must be assigned with just one accountability and that’s the solely cause it ought to change. On this method it is going to make code extra convincible, workable and readable.

For ex :

class Chef{
    enjoyable prepare dinner(){
        println("Cooking")
    }

    enjoyable orderIngredients(){
        println("Ordering Components")
    }

    enjoyable manageStaff(){
        println("Managing Workers")
    }
}

enjoyable predominant(){
    val chef = Chef()
    chef.prepare dinner()
    chef.orderIngredients()
    chef.manageStaff()
}

// however
// chef ought to solely prepare dinner

class Chef1{
    enjoyable prepare dinner(){
        println("Cooking")
    }
}

class Supervisor{
    enjoyable orderIngredients(){
        println("Ordering Components")
    }

    enjoyable manageStaff(){
        println("Managing Workers")
    }
}

Enter fullscreen mode

Exit fullscreen mode

let’s take an instance of frequent usecase, once we are dealing with the authentication for our app,


class LoginMethod(
    non-public val firebaseAuth: FirebaseAuth
) {
    enjoyable signIn(e mail: String, password: String) {
        // Enter validation
        if (e mail.isEmpty() || password.isEmpty()) {
            throw IllegalArgumentException("Invalid enter")
        }

        // Authentication
        strive {
            firebaseAuth.signInWithEmailAndPassword(e mail, password)
            println("Login profitable")
        } catch (e: Exception) {
            // Error dealing with
            println("Login failed: ${e.message}")
        }
    }
}

Enter fullscreen mode

Exit fullscreen mode

Right here we’re making this signIn operate to deal with extra accountability than it ought to do, like validating the fields and dealing with errors additionally

This is how one can repair it,

class LoginMethod(
    non-public val firebaseAuth: FirebaseAuth,
    non-public val fieldValidator: FieldValidator,
    non-public val errorHandler: ErrorHandler
) {
    enjoyable signIn(e mail: String, password: String) {
        // Enter validation
        if(!fieldValidator.validateEmail(e mail) || !fieldValidator.validatePassword(password)) {
            throw IllegalArgumentException("Invalid Format")
        }

        // Authentication
        strive {
            firebaseAuth.signInWithEmailAndPassword(e mail, password)
            println("Login profitable")
        } catch (e: Exception) {
            // Error dealing with
            errorHandler.handleError(e)
        }
    }
}

class FieldValidator {
    enjoyable validateEmail(e mail: String): Boolean {
        return e mail.incorporates("@")
    }

    enjoyable validatePassword(password: String): Boolean {
        return password.size >= 6
    }
}

class ErrorHandler {
    enjoyable handleError(e: Exception) {
        println("An error occurred: ${e.message}")
    }
}
Enter fullscreen mode

Exit fullscreen mode

Right here our signIn operate can solely be chargeable for login , not for checking validation or logging error.

Open/ Closed Precept ( OCP )

Right here this precept states that, a category ought to open for extension however closed for modification.

Let’s take an instance

Actual world instance , say there’s a automobile and it has music system which might play music by way of usb.
Now say, music system these days are coming with bluetooth connectivity additionally, then the engineers is not going to open every a part of this music system, and set up bluetooth module and shut it, proper. For one time it ought to really feel handy however for giant case positively not.
As a substitute they’ll lengthen one frequent module, the place any new modules like BLE, WiFi could be linked, on this method they do not have to change the system each time.

Let’s perceive with programming,

open class Form {
    open enjoyable draw() {
        println("Drawing Form")
    }
}
Enter fullscreen mode

Exit fullscreen mode

Right here if we need to change this class for each completely different form, then it would change the code for the entire app, wherever you’re utilizing this.
Right here intention is we should always not modify how the category behaves or works.
so on this case , the category Form shouldn’t be modified to accomodate new forms of shapes


open class Form {
    open enjoyable draw() {
        println("Drawing Form")
    }
    open enjoyable drawSquare() {
        println("Drawing Form")
    }
    open enjoyable drawRect() {
        println("Drawing Form")
    }
}
Enter fullscreen mode

Exit fullscreen mode

As a substitute you possibly can modify this as


open class Form {
    open enjoyable draw() {
        println("Drawing Form")
    }
}

class Sq. : Form() {
    override enjoyable draw() {
        println("Drawing Sq.")
    }
}

class Circle : Form() {
    override enjoyable draw() {
        println("Drawing Circle")
    }
}
Enter fullscreen mode

Exit fullscreen mode

Will submit different rules very quickly, until then you probably have any suggestion, i am open to any dialogue.

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?