<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kumar Rishi</title>
    <description>The latest articles on DEV Community by Kumar Rishi (@rishi2062).</description>
    <link>https://dev.to/rishi2062</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1483539%2F6a842502-68cd-47d1-96bf-ce8726422a82.jpeg</url>
      <title>DEV Community: Kumar Rishi</title>
      <link>https://dev.to/rishi2062</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rishi2062"/>
    <language>en</language>
    <item>
      <title>SOLID Principles for Android</title>
      <dc:creator>Kumar Rishi</dc:creator>
      <pubDate>Tue, 11 Jun 2024 18:07:45 +0000</pubDate>
      <link>https://dev.to/rishi2062/solid-principles-for-android-2f5f</link>
      <guid>https://dev.to/rishi2062/solid-principles-for-android-2f5f</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0unte1kf83p9j7nevlhd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0unte1kf83p9j7nevlhd.png" alt="Solid Principle For android" width="365" height="138"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this article we will see the remaining Principles,&lt;br&gt;
if you haven't went through the first two principle &lt;br&gt;
refer its first part.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;L - Liskov Substitution Principle (LSP)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This principle says that we need to ensure that subclasses can replace their base classes without altering the correctness of the program.&lt;/p&gt;

&lt;p&gt;Here its objective is , whenever we use subclasses, it should be substitutable in a manner it should not give any error and ofcourse should work without changing the base class behaviour.&lt;/p&gt;

&lt;p&gt;Let's take a real example - Say a store have generic payment system, having payment processed and refund processed category, now say store wants to include a new payment system Gift card, so here refund is not allowed, so if this giftCard throws exception on invoking refundProcess then it violates the LSP principle.&lt;/p&gt;

&lt;p&gt;You can correct it as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Payment{
    fun paymentProcessed()
}

interface Refund{
    fun refundProcessed()
}

class CashPayment : Payment,Refund {
    override fun paymentProcessed() {
        println("Cash Payment Processed")
    }

    override fun refundProcessed() {
        println("Cash Refund Processed")
    }
}

class GiftCardPayment : Payment,Refund {
    override fun paymentProcessed() {
        println("Gift Card Payment Processed")
    }

    override fun refundProcessed() {
        println("Refund for GiftCard is Not Supported")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here it may look like, we can avoid directly but in big scenario, we need to ensure the if there is any restriction for one of the subclasses, it should execute without any exception.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I - Interface Segregation Principle (ISP)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Probably the easiest principle to understand,&lt;br&gt;
This principle says that, the methods that are declared in the interface should not be forced to implement, if its subclass doesn't requires it.&lt;/p&gt;

&lt;p&gt;Lets say a person can do many jobs like engineer, doctor, Civil service, but treating a patient is not something engineers can do, so  to adhere with ISP, we can create separate interfaces from person then we can use them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Person {
    fun engineer()

    fun doctor()

    fun teacher()
}

class Engineer : Person {
    override fun engineer() {
        println("Engineering")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here this code will give error, as engineer class should not implement other methods, but here it is forced to.&lt;br&gt;
To fix this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
interface Person {
    fun engineer(){}

    fun doctor(){}

    fun teacher(){}
}

class Engineer : Person {
    override fun engineer() {
        println("Engineering")
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here this code is just an example on how you can adhere to ISP.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;D - Dependency Inversion Principle&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This principle says that, for any implementations, we should depend on their abstractions and not on their concrete implementation.&lt;/p&gt;

&lt;p&gt;For this i will give two examples, &lt;br&gt;
first is, If you are following Android best practices, then you might have noticed that, if you have repository in your app then in your UI layer you were using repository abstraction and in data layer, you were using that repositoryImplementation, this is one example of DIP, &lt;/p&gt;

&lt;p&gt;another example would be, say you are using authentication methods in your app, then instead of having a concrete extension, you can make it abstract and then use its function.&lt;/p&gt;

&lt;p&gt;This helps in various ways, first your UI layer or whoever is using the abstraction will only know what is happening and how it is happening will be hidden. second when you use generic abstraction, it gives you a vast way of implementation on how that abstraction should work.&lt;/p&gt;

&lt;p&gt;Let's see with the code,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class LoginMethod(
    private val firebaseAuth: FirebaseAuth,
    private val fieldValidator: FieldValidator,
    private val errorHandler: ErrorHandler
) {
    fun signIn(email: String, password: String) {
        // Authentication
        try {
            firebaseAuth.signInWithEmailAndPassword(email, password)
            println("Login successful")
        } catch (e: Exception) {
            // Error handling
            errorHandler.handleError(e)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the Firebase Auth is concrete implementation, now it has two cons, first your subclass is also aware of how it is working second if you want to use other authentications, we are restricted to do so here.&lt;/p&gt;

&lt;p&gt;Let's Fix it&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LoginMethod(
    private val authentication: Authenticator,
    private val fieldValidator: FieldValidator,
    private val errorHandler: ErrorHandler
) {
    fun signIn(email: String, password: String) {
        // Authentication
        try {
            authentication.signInWithEmailAndPassword(email, password)
            println("Login successful")
        } catch (e: Exception) {
            // Error handling
            errorHandler.handleError(e)
        }
    }
}

interface Authenticator{
    fun signInWithEmailAndPassword(email: String, password: String)

    fun signInWithGoogle()
}

class AuthImpl(
    private val firebaseAuth: FirebaseAuth
) : Authenticator {
    override fun signInWithEmailAndPasswordWithFirebase(email: String, password: String) {
        firebaseAuth.signInWithEmailAndPassword(email, password)
    }

    override fun signInWithGoogle() {
        signInWithGoogle()
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hope till now, if you are with me, this article might have helped you in understanding these principles. But in order to make it muscle memory you need to start using these principles.&lt;br&gt;
If you have any suggestions, open for any discussions.&lt;/p&gt;

</description>
      <category>android</category>
      <category>opensource</category>
      <category>solidprinciples</category>
      <category>oops</category>
    </item>
    <item>
      <title>SOLID Principles for Android</title>
      <dc:creator>Kumar Rishi</dc:creator>
      <pubDate>Sun, 09 Jun 2024 09:19:25 +0000</pubDate>
      <link>https://dev.to/rishi2062/solid-principles-for-android-4f62</link>
      <guid>https://dev.to/rishi2062/solid-principles-for-android-4f62</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0unte1kf83p9j7nevlhd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0unte1kf83p9j7nevlhd.png" alt="Solid Principle For android" width="365" height="138"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As a developer, there comes a time when we have to learn principles for moving ahead in career. For some this topic might be new, for some they are already experienced on these principles. I will try to make sure, this article may come in help for both of them.&lt;/p&gt;

&lt;p&gt;So Let's Begin,&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Every letter in SOLID , represents one principle.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Fist Principle that we will talk about&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;S - Single Responsibility Principle ( SRP )&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This one is easy to understand, but it might take you some time to get in memory muscle.&lt;/p&gt;

&lt;p&gt;Real world Example - Let's say you are a chef in a restaurant, now you should be responsible for making the food right.&lt;br&gt;
Now if you given also the task of handling the staffs in kitchen or serving food, will make the work complicated right.&lt;/p&gt;

&lt;p&gt;That's how in programming, a method that you have declared should be assigned with only one responsibility and that is the only reason it should change. In this manner it will make code more convincible, workable and readable.&lt;/p&gt;

&lt;p&gt;For ex :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Chef{
    fun cook(){
        println("Cooking")
    }

    fun orderIngredients(){
        println("Ordering Ingredients")
    }

    fun manageStaff(){
        println("Managing Staff")
    }
}

fun main(){
    val chef = Chef()
    chef.cook()
    chef.orderIngredients()
    chef.manageStaff()
}

// but
// chef should only cook

class Chef1{
    fun cook(){
        println("Cooking")
    }
}

class Manager{
    fun orderIngredients(){
        println("Ordering Ingredients")
    }

    fun manageStaff(){
        println("Managing Staff")
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let's take an example of common usecase, when we are handling the authentication for our app,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class LoginMethod(
    private val firebaseAuth: FirebaseAuth
) {
    fun signIn(email: String, password: String) {
        // Input validation
        if (email.isEmpty() || password.isEmpty()) {
            throw IllegalArgumentException("Invalid input")
        }

        // Authentication
        try {
            firebaseAuth.signInWithEmailAndPassword(email, password)
            println("Login successful")
        } catch (e: Exception) {
            // Error handling
            println("Login failed: ${e.message}")
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are making this signIn function to handle more responsibility than it should do, like validating the fields and handling errors also&lt;/p&gt;

&lt;p&gt;Here's how you can fix it,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LoginMethod(
    private val firebaseAuth: FirebaseAuth,
    private val fieldValidator: FieldValidator,
    private val errorHandler: ErrorHandler
) {
    fun signIn(email: String, password: String) {
        // Input validation
        if(!fieldValidator.validateEmail(email) || !fieldValidator.validatePassword(password)) {
            throw IllegalArgumentException("Invalid Format")
        }

        // Authentication
        try {
            firebaseAuth.signInWithEmailAndPassword(email, password)
            println("Login successful")
        } catch (e: Exception) {
            // Error handling
            errorHandler.handleError(e)
        }
    }
}

class FieldValidator {
    fun validateEmail(email: String): Boolean {
        return email.contains("@")
    }

    fun validatePassword(password: String): Boolean {
        return password.length &amp;gt;= 6
    }
}

class ErrorHandler {
    fun handleError(e: Exception) {
        println("An error occurred: ${e.message}")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here our signIn function can only be responsible for login , not for checking validation or logging error.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Open/ Closed Principle ( OCP )&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here this principle states that, a class should open for extension but closed for modification.&lt;/p&gt;

&lt;p&gt;Let's take an example  &lt;/p&gt;

&lt;p&gt;Real world example , say there is a car and it has music system which can play music via usb.&lt;br&gt;
Now say, music system nowadays are coming with bluetooth connectivity also, then the engineers will not open each part of this music system, and install bluetooth module and close it, right. For one time it should feel convenient but for large case definitely not.&lt;br&gt;
Instead they can extend one common module, where any new modules like BLE, WiFi can be connected, in this way they don't have to modify the system every time.&lt;/p&gt;

&lt;p&gt;Let's understand with programming,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;open class Shape {
    open fun draw() {
        println("Drawing Shape")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here if we want to change this class for every different shape, then it might change the code for the whole app, wherever you are using this.&lt;br&gt;
Here intention is we should not modify how the class behaves or works.&lt;br&gt;
so in this case , the class Shape should not be modified to accomodate new types of shapes&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
open class Shape {
    open fun draw() {
        println("Drawing Shape")
    }
    open fun drawSquare() {
        println("Drawing Shape")
    }
    open fun drawRect() {
        println("Drawing Shape")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead you can modify this as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
open class Shape {
    open fun draw() {
        println("Drawing Shape")
    }
}

class Square : Shape() {
    override fun draw() {
        println("Drawing Square")
    }
}

class Circle : Shape() {
    override fun draw() {
        println("Drawing Circle")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Will post other principles very soon, till then if you have any suggestion, i'm open to any discussion.&lt;/p&gt;

</description>
      <category>android</category>
      <category>androiddev</category>
      <category>opensource</category>
      <category>solidprinciples</category>
    </item>
    <item>
      <title>Jetpack Compose -Difference between mutableStateOf() and derivedStateOf()</title>
      <dc:creator>Kumar Rishi</dc:creator>
      <pubDate>Wed, 29 May 2024 13:07:27 +0000</pubDate>
      <link>https://dev.to/rishi2062/jetpack-compose-difference-between-mutablestateof-and-derivedstateof-43m9</link>
      <guid>https://dev.to/rishi2062/jetpack-compose-difference-between-mutablestateof-and-derivedstateof-43m9</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foiffoj6yhssk0904s4xe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foiffoj6yhssk0904s4xe.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hey Guys!!, Well thought of sharing my experience on those concepts, which might gets overlooked quite frequently.&lt;br&gt;
Have You ever wondered the exact usecase of mutableStateOf() and derivedStateOf()&lt;/p&gt;

&lt;p&gt;Let's say when you have some variable and you want to trigger an UI change basically recomposition , when that variable changes, most likely you will use mutableStateOf()&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

val count = mutableStateOf(1)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;However to make sure recomposition value must be stored you need to use remember, maybe next time i will focus on this&lt;/p&gt;

&lt;p&gt;Now think of a situation, where you are storing some value, on that value change you automatically want to modify other variable, then derivedStateOf() is preferable&lt;br&gt;
for ex :-&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

val height by remember{ mutableStateOf(10) }
val width by remember{ mutableStateOf(10) }
val area by remember{ derivedStateOf(height * width) }



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;in this way area will automatically change whenever there is any change in dimensions variables and composable observing area will also trigger recomposition.&lt;br&gt;
In this manner it becomes more readable, less error prone&lt;/p&gt;

&lt;p&gt;Now you may think this can be achieved by mutableStateOf() with something like&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

val height by remember{ mutableStateOf(10) }
val width by remember{ mutableStateOf(10) }
val area by remember{ mutableState(height * width) }



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here if there is any change in height and width , you need to manually update it&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

area = height * width



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can also do this by &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

val height by remember{ mutableStateOf(10) }
val width by remember{ mutableStateOf(10) }
val area by remember(height,width){ mutableState(height * width) }



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;now if there is any change in height and weight , area will also update&lt;/p&gt;

&lt;p&gt;but here also the main difference is restricting composition count , when you are having long calculations and variable that changes very frequently,&lt;/p&gt;

&lt;p&gt;Lets end this with my supporting word for last statement,&lt;br&gt;
where i found this good example at StackOverFlow&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@Composable
fun CounterButton() {
    val clicks = remember { mutableStateOf(0) }
    val counter = remember(clicks.value / 5) { mutableStateOf(clicks.value / 5) }

    Button(
        onClick = { clicks.value++ }
    ) {
        Text("${counter.value} clicked")
    }
}



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;counter variable is supposed to be change on every 5 clicks, say you pressed 30 clicks so then button will recompose on every click but the CounterButton() method will compose 5 times,&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

@Composable
fun CounterButton() {
    val clicks = remember { mutableStateOf(0) }
    val counter = remember { derivedStateOf { clicks.value / 5 } }

    Button(
        onClick = { clicks.value++ }
    ) {
        Text("${counter.value} clicked")
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;here CounterButton() will have no recomposition, &lt;br&gt;
But there is a huge pitfall or drawback for this, as it will not change the reference of the state object instead rely on state value.&lt;br&gt;
You can learn more here - &lt;a href="https://medium.com/@bagadeshrp/derivedstateof-pitfall-jetpack-compose-9487ff1cc6ee" rel="noopener noreferrer"&gt;DerivedState Pitfall&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Already the article went long, but if you are here, Thanks a lot for you time and if you want to update any fact , logic to lets bombard comment section and happy coding.&lt;/p&gt;

</description>
      <category>android</category>
      <category>jetpackcompose</category>
      <category>androiddev</category>
      <category>opensource</category>
    </item>
  </channel>
</rss>
