<?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 Gaurang Shaha on Medium]]></title>
        <description><![CDATA[Stories by Gaurang Shaha on Medium]]></description>
        <link>https://medium.com/@gaurang.shaha_6814?source=rss-d79f56c7947a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sVI9YLq7y81EAgFzndU5Yg.jpeg</url>
            <title>Stories by Gaurang Shaha on Medium</title>
            <link>https://medium.com/@gaurang.shaha_6814?source=rss-d79f56c7947a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 23:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gaurang.shaha_6814/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[Storybook]]></title>
            <link>https://medium.com/swlh/storybook-e8aa6ca4a433?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8aa6ca4a433</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[preview]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 17:10:16 GMT</pubDate>
            <atom:updated>2023-11-16T17:10:16.884Z</atom:updated>
            <content:encoded><![CDATA[<p>A library that helps you create a list of components by scanning compose functions that are marked with @Preview annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwRY1dDGeE4JpaE1BnOP5A.jpeg" /></figure><p>Jetpack Compose is a modern toolkit for building native Android UI. Using Compose, you can build your user interface by defining a set of <em>composable</em> functions that take in data and emit UI elements. In other words, we can create a small composable function that acts as a common component and can be reused in several places.</p><p>Recently, I was reviewing a project that is using Compose for UI. Multiple teams are working on different features and they have created separate UI implementations for the same element in their respective modules. It created code duplication and increased the effort of changing behavior. The better idea would be to extract them into a common module specially created for common UI components.</p><p>While making the refactoring, we realized that we would need a list of components that are already available. By doing so we can have a single source of truth about components and don’t have to go to each component and wait for Android Studio to render it. It will also help us to communicate better between UI designers, BA, and developers by using the names of components.</p><p>As the number of components and developers grows over time, it becomes a bit difficult to properly update the list. At that point in time, I thought wouldn’t it be great if this list could be somehow autogenerated so we don&#39;t have to maintain it? We have already created the previews for our components so I have decided to write a KSP that will search for functions with @Preview annotation and create a list of it. This library is an outcome of the problem that we have faced.</p><p><a href="https://github.com/GaurangShaha/Storybook">GitHub - GaurangShaha/Storybook</a></p><p>Enough of the talks let&#39;s see it in action,</p><h4>Integration</h4><p>In your setting.gradle add an entry for Jitapack,</p><pre>dependencyResolutionManagement {<br>  repositories {<br>    maven { url &#39;https://jitpack.io&#39; }<br>  }<br>}</pre><p>Now in your build.gradle add the following lines,</p><pre>plugins {<br>    id &quot;com.google.devtools.ksp&quot; version &quot;ksp_version&quot; <br>}<br><br>dependencies {<br>    ksp &quot;com.github.GaurangShaha:Storybook:1.0.2&quot;<br>}</pre><p>The KSP version is dependent on the Kotlin compiler that you are using. You can find the KSP versions <a href="https://github.com/google/ksp/releases">here</a>.</p><p>Once you rebuild the project, it will generate a compose function with the name as the name of the module appended by Storybook. Eg. a module with the name ui-component will generate a compose function with the name UiComponentStorybook. You can use this function to show the list wherever you want to display it.</p><p>Using this function user can do the following things,</p><ul><li>See the list of components. It will be achieved by scanning functions marked with @Preview annotation and are not private. The name of the component will be derived from the name of a function.</li><li>Search the component in a list with its name.</li><li>On tapping any item in the list, the user can see the component rendered.</li></ul><blockquote>Note — The function marked with @Preview annotation need to be public or internal in order to get listed.</blockquote><p>It supports @Preview annotation out-of-the-box. If you have created any custom annotation for preview purposes, you can pass its fully qualified name as an argument to KSP in your build.gradle file.</p><pre>ksp {<br>    arg(&quot;extendedPreviews&quot;, &quot;com.flea.market.ui.preview.FleaMarketPreviews&quot;)<br>}</pre><p>If you have multiple annotations for preview, pass them as a comma-separated string.</p><p>Following is the recording from the samples that I have created,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_pSynzVZ4_YghrnTAZ8Bw.gif" /><figcaption>UI created by the Storybook library.</figcaption></figure><p><a href="https://github.com/GaurangShaha/Storybook">GitHub - GaurangShaha/Storybook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8aa6ca4a433" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/storybook-e8aa6ca4a433">Storybook</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance vs. Composition]]></title>
            <link>https://medium.com/@gaurang.shaha_6814/inheritance-vs-composition-cfd48fd87e06?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfd48fd87e06</guid>
            <category><![CDATA[oops-concepts]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 03:50:34 GMT</pubDate>
            <atom:updated>2020-09-15T03:50:34.888Z</atom:updated>
            <content:encoded><![CDATA[<p>Is Inheritance evil 😈 and Composition benign 😇?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krik-Q3zEj64L_FOLemOfg.jpeg" /><figcaption>Picture credit: <a href="https://realpython.com/">realpython.com</a></figcaption></figure><p>It all started with the SonarQube code quality report. We have integrated SonarQube in the existing application and got a report containing code smells for duplicate code. I and my colleague started discussing the possible ways to refactor the code and caught up in the dilemma of whether to go for Inheritance or Composition. After reading several articles and putting a lot of thought on it we agreed to use them on a case to case basis. Here I am writing my understanding based on which we took the decision. So let’s start with defining what is it.</p><p>In object-oriented programming, we represent the real word object with classes a.k.a types. Classes share the relationships between them. Inheritance and Composition are the types of relationships between the classes.</p><h4>Inheritance</h4><blockquote>Inheritance is when you design types around what they are.</blockquote><p>It is a type of relationship where a child acquires all behaviors from the parent. This is one of the fundamental principles of Object-Oriented programming. In this type of relationship, a child and the base class will have tight coupling between them. In other words, any change in the implementation details of the base class will impact the child&#39;s class.</p><h4>Composition</h4><blockquote>Composition is when you design types around what they do.</blockquote><p>It is a type of relationship where a complex class is created combining the other classes. This is also the most important principles of Object-Oriented programming. In this type of relationship, both of the classes will have loose coupling between them. In other words, any change in the implementation details of the one class will not impact another class.</p><h4><strong>What’s the fuzz about this?</strong></h4><p>Inheritance and Composition are both fundamental, so what’s the fuzz about this? The real problem starts when we think in all cases one can replace the other.</p><p>Though the definition of inheritance is simple, it can become complicated when used improperly. Inheritance is more of an abstraction that we can only talk about, not touch directly. Whereas, the purpose of composition is to make wholes out of parts.</p><p>Though it is possible to mimic inheritance using composition in all situations, it is not wise to do so.</p><h4>How to decide Inheritance or Composition?</h4><p>The inheritance can be applied if the following statements hold true</p><ol><li>The subclass is a proper subtype of the superclass.</li><li>The subclass follows the <a href="https://proandroiddev.com/liskov-substitution-principle-135c543218b1">Liskov Substitution principle</a>.</li><li>The superclass’s implementation is appropriate for the subclass.</li><li>The enhancements made by the subclass are primarily addition or change to the superclass’s behavior.</li></ol><p>If the child class is removing the functionality of the base class, we should rethink the relationship. Inheritance forces us to predict the future and structure the code accordingly. We humans are not good at predicting the future so we should be using inheritance sparingly.</p><p>Generally, the above conditions satisfy if we are writing</p><ul><li>Framework or framework extension.</li><li>Higher-level classes defined for software architecture purposes e.g. BaseViewModel, BasePresenter, etc.</li><li>Differential programming.</li></ul><p>If you are not doing the things mentioned above then it is advisable to use composition. It clearly provides benefits over the inheritance and keeps code loosely coupled. You can easily mix and match the behaviors with the help of composition that will help you in accomodating upcoming changes.</p><p>In most cases, we should be using the composition but it is not a golden bullet.</p><p>Use inheritance sparingly. Don’t use it just for sake of reusing the code. When you’re considering using inheritance, ask yourself whether the subclass really is a more specialized version of the superclass? Does it follow the <a href="https://proandroiddev.com/liskov-substitution-principle-135c543218b1">Liskov Substitution principle</a>? Would it make more sense to use composition at this place?</p><p>It’s not good to demonize the inheritance because we misuse it. It is like saying the car is not good as it can not fly or the hammer is a waste as it can not screw the nuts.</p><p>I hope this article will help you to make the proper decision.</p><p>Happy coding!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfd48fd87e06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Inversion Principle]]></title>
            <link>https://proandroiddev.com/dependency-inversion-principle-4cde793c5bb3?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cde793c5bb3</guid>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 19:52:26 GMT</pubDate>
            <atom:updated>2020-09-07T17:11:59.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fNU6r9TZsGHHihVShW-73Q.jpeg" /></figure><blockquote>One should depend upon abstractions, not on the concrete implementation.</blockquote><p>In a typical system, we have some higher-level, middle-level, and lower-level modules. If the system depends on the concrete implementation, then the higher-level module will depend on the middle-level modules. The middle-level module will depend on several lower-level modules. Control also flows in the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*u_54MQOiE1dDXLLMPbjWjA.png" /></figure><p>Now any change in the lower-level module will force the middle and higher-level modules to recompile as they are directly dependant on the lower-level module. In other words, a simple change in details will force the higher-level policy to change. This is fundamentally incorrect. Our higher-level policy should be immune to any changes in details that can happen in a lower-level module. To protect our higher-level policy from these changes we have to provide the abstraction in places where these changes can happen most.</p><p>Let’s consider a typical example of a terms and conditions screen. The user will be presented with terms and conditions, he has two buttons to accept and deny it. We have to save the user’s selection inside the local storage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b653c1acb71a6bde2569f0ddf40f82d5/href">https://medium.com/media/b653c1acb71a6bde2569f0ddf40f82d5/href</a></iframe><p>Now the product team decides that instead of storing data on local storage, it should be sent to the server. Making these changes will force the entire codebase to recompile. Which implies that there is rigidity in code. Separation of concerns is also not followed here.</p><p>Let’s divide this class into two different modules. The first module will deal with UI, the second will for managing data storage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c023ab3c564c7203fe232cb503654ea/href">https://medium.com/media/9c023ab3c564c7203fe232cb503654ea/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2ffbd8790a3c1e5bf4cce1e9b01d74/href">https://medium.com/media/5d2ffbd8790a3c1e5bf4cce1e9b01d74/href</a></iframe><p>These two will be part of our UI module. Now from the TermsAndConditionsPresenter, if we directly access the concrete implementation of TermsAndConditionsRepository class it will create a direct dependency. Any changes made in TermsAndConditionsRepository will force TermsAndConditionsPresenter and TermsAndConditionsActivity to recompile.</p><p>Instead of doing it, I will create an interface TermsAndConditionsRepository and add it to the UI module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63451c62d1dae9d6944de722dde362b/href">https://medium.com/media/a63451c62d1dae9d6944de722dde362b/href</a></iframe><p>Inside the second module, we will have the implementation of this interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42794d23da22b4ad19427715d3862847/href">https://medium.com/media/42794d23da22b4ad19427715d3862847/href</a></iframe><p>As we have added an interface between TermsAndConditionsPresenter and TermsAndConditionsRemoteRepository, we have reversed the direction of dependency. Now our data management module depends on the UI module. Any changes in the data management module won&#39;t force any of the other modules to recompile. Now we can easily change the storage of data from the local storage to remote server and the rest of the code will not know about it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48df797630da69d2cb9fc603b61c2165/href">https://medium.com/media/48df797630da69d2cb9fc603b61c2165/href</a></iframe><p>The second hardest thing in software programming after the naming is managing the dependencies. If we learn to manage them properly most of the issues we face in day to day life will get resolved. We should use abstraction in places where the probability of change is high or we are dealing with code on which we don’t have any control e.g. libraries. This will protect us from future changes, thus make our code more maintainable.</p><ul><li><a href="https://medium.com/@gaurang.shaha_6814/s-o-l-i-d-principles-60e0f91afa6">S.O.L.I.D. Principles</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/single-responsibility-principle-f806c88f4003">Single Responsibility Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/open-closed-principle-5100632df310">Open-Closed Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/liskov-substitution-principle-135c543218b1">Liskov Substitution Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/interface-segregation-principle-3ce39a326dd">Interface Segregation Principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cde793c5bb3" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/dependency-inversion-principle-4cde793c5bb3">Dependency Inversion Principle</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface Segregation Principle]]></title>
            <link>https://proandroiddev.com/interface-segregation-principle-3ce39a326dd?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce39a326dd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[interface-segregation]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 18:30:09 GMT</pubDate>
            <atom:updated>2020-09-07T17:10:52.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QbiHzr9-WCyd2xdJnOhHjw.jpeg" /></figure><blockquote>The clients shouldn’t be forced to implement the methods that they do not use.</blockquote><p>The interface segregation principle (ISP) is about creating very specialized interfaces for the client. It’s a good practice to create interfaces that are understandable from the perspective of the client. The Interface segregation principle encourages us to create different interfaces for different clients. The clients mentioned above are nothing but the classes implementing them.</p><p>Let’s take an example of an application that calculates the area and volume of a given shape. Following is a bad way to implement it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf82a1764222fb620153c298056bccbb/href">https://medium.com/media/cf82a1764222fb620153c298056bccbb/href</a></iframe><p>Now every class that inherits from Shape should provide the implementation for these two methods. We have class Square which inherits from Shape.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b23b8dfb7cf61a0729ccca3d6a7d05a7/href">https://medium.com/media/b23b8dfb7cf61a0729ccca3d6a7d05a7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf1e68cabe26793be40548775b23fdbd/href">https://medium.com/media/cf1e68cabe26793be40548775b23fdbd/href</a></iframe><p>Now as calculate volume does not apply to the square we are returning zero. This is a bad design choice as the clients are not going to need all of the methods. The better solution will be to create two different interfaces for two-dimensional objects and three-dimensional objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/923fbe3f3a335e10b15e56bb3d13f1ba/href">https://medium.com/media/923fbe3f3a335e10b15e56bb3d13f1ba/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bb87d41f2e06e0c2c6de52d9fc83c7f/href">https://medium.com/media/2bb87d41f2e06e0c2c6de52d9fc83c7f/href</a></iframe><p>Now the Square will implement TwoDimensionalShape and Cube will implement ThreeDimensionalShape. In this way, we can decouple code and make it more understandable.</p><ul><li><a href="https://medium.com/@gaurang.shaha_6814/s-o-l-i-d-principles-60e0f91afa6">S.O.L.I.D. Principles</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/single-responsibility-principle-f806c88f4003">Single Responsibility Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/open-closed-principle-5100632df310">Open-Closed Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/liskov-substitution-principle-135c543218b1">Liskov Substitution Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/dependency-inversion-principle-4cde793c5bb3">Dependency Inversion Principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce39a326dd" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/interface-segregation-principle-3ce39a326dd">Interface Segregation Principle</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Liskov Substitution Principle]]></title>
            <link>https://proandroiddev.com/liskov-substitution-principle-135c543218b1?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/135c543218b1</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 17:50:19 GMT</pubDate>
            <atom:updated>2020-09-07T17:10:12.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GzzGH4w9vRBiXYs1nKdZZg.jpeg" /></figure><blockquote>The derived class must be usable through the base class interface, without the need for the user to know the difference.</blockquote><p>This was initially introduced by Barbara Liskov in 1987. Above is the paraphrase of the formula written by her. Let me explain it to you with the Rectangle-Square problem.</p><p>Consider that we have a Rectangle a class written a long ago, now the client wants us to add functionality for Square.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/044a14265ab34223569ad439e75ce9e7/href">https://medium.com/media/044a14265ab34223569ad439e75ce9e7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/757c727488628c22a3d983eb79e19020/href">https://medium.com/media/757c727488628c22a3d983eb79e19020/href</a></iframe><p>Now as every square is a rectangle, so somebody decided to extend the Square class from the Rectangle. Rectangle has two different fields for height and width and Square has only one. To overcome this problem they have decided to override the set height and set width method in Square in such a way that it will update both of the values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/645ef3d80546b0f417dd94abfda114f4/href">https://medium.com/media/645ef3d80546b0f417dd94abfda114f4/href</a></iframe><p>Imagin some user of Rectangle calls the method for set height, he/she will be expecting that doing so the width will not be altered. Suppose now we pass the object of Square to his function. Due to the overridden behavior of Square both of the values will get altered, which leads to some kind of bug in his function. A new production bug will get filed for this.</p><p>After hours and hours of debugging, he/she found that it happened as the object passed to his function was Square, not the Rectangle. Now the easiest way to avoid this bug is to add check whether the object received is Square or not and run the functionality only if it is not Square.</p><p>This fix will force the Rectangle to depend on Square. It will violate the Open-Closed principle and make our code rigid and fragile.</p><p>But we are sure that all squares are rectangle, so we have it <em>isA </em>relationship between them. What really went wrong here? Actually the class Rectangle and Square is a representation of the shape Rectangle and Square. The representatives of things do not share the relationships of the thing they are representing.</p><p>Uncle Bob explains it with an example and I quote:</p><p><em>If anybody is being divorced they will have two lawyers representing him/her and spouse. Though the lawyer represents them, lawyers themselves are not getting the divorce.</em></p><p>So the conclusion is the class Square can not be derived from the class Rectangle. They are two different entities and do not share any relation between them. It will be correct to create different classes for them without inheriting one into another.</p><p>The classes shown below follow the Liskov Substitution Principle. You can easily switch between TermsAndConditionsRemoteRepository and TermsAndConditionsLocalRepository and vice versa without the consumer knowing about it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63451c62d1dae9d6944de722dde362b/href">https://medium.com/media/a63451c62d1dae9d6944de722dde362b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48df797630da69d2cb9fc603b61c2165/href">https://medium.com/media/48df797630da69d2cb9fc603b61c2165/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42794d23da22b4ad19427715d3862847/href">https://medium.com/media/42794d23da22b4ad19427715d3862847/href</a></iframe><ul><li><a href="https://medium.com/@gaurang.shaha_6814/s-o-l-i-d-principles-60e0f91afa6">S.O.L.I.D. Principles</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/single-responsibility-principle-f806c88f4003">Single Responsibility Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/open-closed-principle-5100632df310">Open-Closed Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/interface-segregation-principle-3ce39a326dd">Interface Segregation Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/dependency-inversion-principle-4cde793c5bb3">Dependency Inversion Principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=135c543218b1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/liskov-substitution-principle-135c543218b1">Liskov Substitution Principle</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open-Closed Principle]]></title>
            <link>https://proandroiddev.com/open-closed-principle-5100632df310?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5100632df310</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 16:14:09 GMT</pubDate>
            <atom:updated>2020-09-12T18:56:11.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VTTQMRvVRxdIYsRIEL5M8A.jpeg" /></figure><blockquote>A class or module should be open for extension and closed for modification.</blockquote><p>This principle was introduced by Bertrand Meyer. According to him class or module should be open for extension and closed for modification. In other words, you should be able to change the behavior of the class or module without changing the existing code.</p><p>What the heck?🙄 Is it really possible?🤔 This was the first word that came out of my mouth when I read it for the first time. Actually we do it oftentimes; let&#39;s decode it with an example.</p><p>Let’s consider a typical example of a terms and conditions screen. The user will be presented with terms and conditions, he has two buttons to accept and deny it. We have to save the user’s selection inside the local storage.</p><p>Below is the crude way to implement the functionality. It does not follow any of the good coding practices also violates the open-closed principle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b653c1acb71a6bde2569f0ddf40f82d5/href">https://medium.com/media/b653c1acb71a6bde2569f0ddf40f82d5/href</a></iframe><p>A manager comes to us and says the client has a lot of problems with this application, so he has hired a consultant. They have a new idea, the client wants to provide two versions of this software. In the free version, data will be stored locally on the device and in the paid version it will be stored remotely on the server.</p><p>Now we have to tell our manager that, we will be able to add the functionality for the store it on the remote server but we have to deploy both functionalities together. As per the current design, there is no way to separate the functionality. This called immobility.</p><p>When we add the functionality for storing data on a remote server the UI and business logic will get recompiled, this is rigidity.</p><p>Also, we have to add a check whether the account is paid or free and accordingly execute the code for saving the data. There will be several such conditions throughout the codebase making the code fragile.</p><h4>How to apply the Open-Closed principle?</h4><p>Let’s modify this code to avoid these bad symptoms and achieve the objective of paid and free accounts. Let&#39;s segregate the class into two modules, first will be responsible for UI related stuff and second will deal with data storage options.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c023ab3c564c7203fe232cb503654ea/href">https://medium.com/media/9c023ab3c564c7203fe232cb503654ea/href</a></iframe><p>We will continue using activity for UI related stuff. We have also created a presenter that will segregate the business logic from our UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2ffbd8790a3c1e5bf4cce1e9b01d74/href">https://medium.com/media/5d2ffbd8790a3c1e5bf4cce1e9b01d74/href</a></iframe><p>These two classes will be part of our UI module. In the same module, we will be defining the TermsAndConditionsRepository interface which has a method for updating terms and conditions preference. TermsAndConditionsPresenter will always depend on this abstract interface instead of the actual implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63451c62d1dae9d6944de722dde362b/href">https://medium.com/media/a63451c62d1dae9d6944de722dde362b/href</a></iframe><p>Now in the second module, we will be having an implementation of the above interface that will store the data in local storage. I am calling it as TermsAndConditionsLocalRepository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42794d23da22b4ad19427715d3862847/href">https://medium.com/media/42794d23da22b4ad19427715d3862847/href</a></iframe><p>After refactoring this code now we have to make changes to store data on a remote server. Now we will create a new class in another module called TermsAndConditionsRemoteRepository, which will extend the TermsAndConditionsRepository and deal with communication with the server. I am using the Retrofit library for this purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48df797630da69d2cb9fc603b61c2165/href">https://medium.com/media/48df797630da69d2cb9fc603b61c2165/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82b5b178c4955976cf9fd1d9ddd9adf8/href">https://medium.com/media/82b5b178c4955976cf9fd1d9ddd9adf8/href</a></iframe><p>As we have added the TermsAndConditionsRemoteRepository the code inside TermsAndConditionsPresenter and TermsAndConditionsActivity will not be recompiled so we get rid of rigidity.</p><p>There are no if-else conditions as we have separate versions of the application as requested by the client. This will get rid of fragility.</p><p>We will compose the application either with local storage or remote server. This will get rid of immobility.</p><h4>Where to apply this principle?</h4><p>This principle will help us to protect against the changes. That does not mean we have to apply it to each and every class. Practically it is almost impossible to do it considering the time and effort it will take.</p><p>Instead, we should identify the points where an application is prone to changes. Apply this principle only at those points. There are two ways to identify these changes, one is from your previous experience another is from the user’s feedback. By following the Agile methods we will be able to get continuous feedback from the user and with it, we will be able to apply this wherever needed. This is an ongoing process and will evolve with time.</p><ul><li><a href="https://medium.com/@gaurang.shaha_6814/s-o-l-i-d-principles-60e0f91afa6">S.O.L.I.D. Principles</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/single-responsibility-principle-f806c88f4003">Single Responsibility Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/liskov-substitution-principle-135c543218b1">Liskov Substitution Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/interface-segregation-principle-3ce39a326dd">Interface Segregation Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/dependency-inversion-principle-4cde793c5bb3">Dependency Inversion Principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5100632df310" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/open-closed-principle-5100632df310">Open-Closed Principle</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S.O.L.I.D. Principles]]></title>
            <link>https://proandroiddev.com/s-o-l-i-d-principles-60e0f91afa6?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/60e0f91afa6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 07:15:21 GMT</pubDate>
            <atom:updated>2020-09-07T17:04:22.591Z</atom:updated>
            <content:encoded><![CDATA[<p>What are the S.O.L.I.D. principles and why you will need them in your project?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTX5NbS5PFZxUQydg-BoAg.png" /><figcaption>The five pillars of clean code</figcaption></figure><h3>What is S.O.L.I.D.?</h3><p>S.O.L.I.D. is an acronym that represents five principles of object-oriented design. Robert C. Martin a.k.a. Uncle Bob has written a paper in 2000 explaining these principles and their need.</p><ul><li><a href="https://medium.com/@gaurang.shaha_6814/single-responsibility-principle-f806c88f4003"><strong>S</strong>ingle Responsibility Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/open-closed-principle-5100632df310"><strong>O</strong>pen/Closed Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/liskov-substitution-principle-135c543218b1"><strong>L</strong>iskov Substitution Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/interface-segregation-principle-3ce39a326dd"><strong>I</strong>nterface Segregation Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/dependency-inversion-principle-4cde793c5bb3"><strong>D</strong>ependency Inversion Principle</a></li></ul><p>This blog explains the reason why then S.O.L.I.D. principle was suggested. There are dedicated blogs for each of the principles, explaining them thoroughly with some samples.</p><h3>Why we need this?</h3><p>Heraclitus, the Greek philosopher said,</p><blockquote>Change is the only constant</blockquote><p>The application’s requirements will change as time passes. A ton of new features and complexity will get added to the codebase. If the system is poorly designed this will have undesirable effects on the software. The code will start to rot and the software will become hard to maintain.</p><p>Eventually, the effort required to make the simplest of changes to the software becomes so high that the engineers think of redesigning the project. Such redesigns rarely succeed so we should consider this while implementing it for the first time.</p><p>The main cause of software design degradation is well known to us. The requirements have been changing in ways that the initial design did not anticipate. Bit by bit, as the changes continue to pour in the quality of software gets degraded.</p><p>However, we cannot blame the changing requirements for the degradation of quality. S.O.L.I.D. principle will help us avoid some common pitfalls and ensures the high maintainability of the codebase.</p><h3>Symptoms of bad software design</h3><p>The following are the symptoms which show that the software is getting rotten</p><p><strong>Rigidity</strong></p><p>Rigidity is the tendency for software to be difficult to change, even in simple ways. A small change in the lower-level module force all the higher-level modules to make changes in implementation. What begins as a simple one day change needs the entire sprint.</p><p><strong>Fragility</strong></p><p>Fragility is the tendency of the software to break in many places every time it is changed. A small change made in one part of the application often breaks the areas that have no conceptual relationship. As the fragility becomes worse, the probability of breakage increases. Such software is impossible to maintain. Every fix makes it worse, introducing more problems than are solved.</p><p><strong>Immobility</strong></p><p>Immobility is the inability to reuse software from other projects or from parts of the same project. Often time developer realizes that they will be needing some functionality which is already implemented in the application.</p><p>However, the functionality has a lot of coupling making it hard to segregate and reuse. After a thorough analysis, the developer determines that the refactoring has a larger risk to some of the vital functionalities. So the software is simply rewritten instead of reused.</p><p>S.O.L.I.D. Principles can provide a remedy to the above symptoms. The use of these practices tends to reduce code complexity, the coupling between classes, separating responsibilities, and well defining the relations between them. These are simple ways to improve code quality and maintainability.</p><p>In this blog, we discussed the basics of S.O.L.I.D. Principles and why we need them. In the upcoming blog of this series, I will be explaining each of the principles in-depth with some real-life examples, so stay tuned. Let me know your thoughts in the comments.</p><ul><li><a href="https://medium.com/@gaurang.shaha_6814/single-responsibility-principle-f806c88f4003">Single Responsibility Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/open-closed-principle-5100632df310">Open-Closed Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/liskov-substitution-principle-135c543218b1">Liskov Substitution Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/interface-segregation-principle-3ce39a326dd">Interface Segregation Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/dependency-inversion-principle-4cde793c5bb3">Dependency Inversion Principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60e0f91afa6" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/s-o-l-i-d-principles-60e0f91afa6">S.O.L.I.D. Principles</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Responsibility Principle]]></title>
            <link>https://proandroiddev.com/single-responsibility-principle-f806c88f4003?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f806c88f4003</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 07:14:29 GMT</pubDate>
            <atom:updated>2020-09-07T17:05:04.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*1funDIH0LF3KaAOICcxuSw.png" /><figcaption>Picture Credit: LearnStuff.io</figcaption></figure><blockquote>A class should have one and only one reason to change.</blockquote><p>We create a software application to solve the problems of the real world. We generally divide software into modules, and modules are further divided into classes. The Single Responsibility Principle (SRP) states that each software module should have one and only one reason to change. In other words, one should gather together the things that change for the same reasons. Separate those things that change for different reasons.</p><p><strong>What qualifies “Reason for Change”?</strong></p><p>Every class or module has its own predefined responsibility. It responds to some person in the real world, most probably he/she will be responsible for the change request. Generally, we should structure our code in such a way that changes should be requested by only one person.</p><p>The reason for the change is nothing but a change in the original responsibility of the software. A bug or refactoring can not be considered as a reason for change as they are not the responsibility of software, rather it is the responsibility of the developer.</p><p>The single responsibility does not mean having a single method inside a class or creating a separate class for every small functionality even those are related and have a single reason to change.</p><p>Enough of theoretical discussion let me explain it with an example. Let’s consider a typical example of a terms and conditions screen. The user will be presented with terms and conditions, he has two buttons to accept and deny it. We have to save the user’s selection inside the local storage.</p><p>Back in the days when I started programming, I tend to do it all in Activity itself. It was total chaos, this is how it used to look.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b653c1acb71a6bde2569f0ddf40f82d5/href">https://medium.com/media/b653c1acb71a6bde2569f0ddf40f82d5/href</a></iframe><p>Now let’s try to apply the single responsibility principle for this piece of code. There can be three reasons for changes in this class, in other words, there can be three different people whose change request will modify this class</p><ul><li>UI Design Engineer - Some new kind of UI design trend is in the market and the UI design team wants to incorporate it into an existing application so they can request a change.</li><li>Software Architect - We are using local storage to save the user’s preference. Now due to the latest security measures, we have to store that information on to our server. In this scenario, the software architect will request a change.</li><li>Legal Advisor - There are some changes in existing terms and conditions. The new terms and conditions should be presented to the user whenever he lands on the screen so there can be a change request.</li></ul><p>Now as we are clear on the potential change point let us create a class for each of them.</p><p>We will continue using activity for UI related stuff. Any further changes from the UI design engineer will affect this class only.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c023ab3c564c7203fe232cb503654ea/href">https://medium.com/media/9c023ab3c564c7203fe232cb503654ea/href</a></iframe><p>Software architects can ask us to save preference on a local or remote location. Let’s create a class that can deal with persisting the user’s preference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f40974e6dae92579077523f91a8ac6b/href">https://medium.com/media/7f40974e6dae92579077523f91a8ac6b/href</a></iframe><p><em>The better solution will be to have a repository pattern implemented to take care of this situation. For the sake of simplicity, I have chosen to create a simple class. </em><a href="https://youtu.be/mb6bwnEaZ3U"><em>Here</em></a><em> you can find more details about the repository pattern.</em></p><p>The legal advisor suggests some modifications in terms and conditions. This code neither belongs to repository nor UI, it is a business requirement. We can use ViewModel or Presenter that will isolate these kinds of requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53da909432523edaaf24f570f88bf233/href">https://medium.com/media/53da909432523edaaf24f570f88bf233/href</a></iframe><p><em>The better solution is to write an interface containing contracts for the presenter and view to decouple them. For the sake of simplicity, I have chosen to use the class directly.</em></p><p>Doing these changes we have isolated the effects of probable changes. Changes will be more specific and will not pose a risk of functionality breakage from some unrelated part. Another substantial benefit is the class that has only one responsibility is much easier to explain, understand, and implement. This reduces the number of bugs, improves your development speed.</p><ul><li><a href="https://medium.com/@gaurang.shaha_6814/s-o-l-i-d-principles-60e0f91afa6">S.O.L.I.D. Principles</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/open-closed-principle-5100632df310">Open-Closed Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/liskov-substitution-principle-135c543218b1">Liskov Substitution Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/interface-segregation-principle-3ce39a326dd">Interface Segregation Principle</a></li><li><a href="https://medium.com/@gaurang.shaha_6814/dependency-inversion-principle-4cde793c5bb3">Dependency Inversion Principle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f806c88f4003" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/single-responsibility-principle-f806c88f4003">Single Responsibility Principle</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[May the power of Coroutine be with you…]]></title>
            <link>https://medium.com/globant/may-the-power-of-coroutine-be-with-you-e345cb5f82e1?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e345cb5f82e1</guid>
            <category><![CDATA[fusedlocationapi]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[location-update]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 17:03:52 GMT</pubDate>
            <atom:updated>2023-12-13T03:03:22.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Using Coroutine to get rid of callbacks &amp; asynchronous programming with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*zxx4iQAG4HilOIQqDKpxJw.jpeg" /></figure><p>Kotlin’s <a href="https://kotlinlang.org/docs/reference/coroutines-overview.html">coroutines</a> introduce a new style of concurrency that can be used on Android to simplify asynchronous code. It was introduced in Kotlin in 1.3, and since then I have been using it extensively for doing asynchronous programming. Along the way, I have learned a few use cases, in a way it surprised me a lot. Basic knowledge of coroutine is a prerequisite for understanding the following concepts.</p><h3>Convert a callback to a suspended function</h3><p>Kotlin provides a nice and fluent API to convert a callback to a suspended function. Kotlin provides a builder <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html">SuspendCancellableCoroutine</a> which will act as an adapter between the coroutine world and the callback-based world.</p><p>It will need a lambda as input, which will be executed and immediately suspended. cancellableContinuation will be provided, using which we can resume the execution at a later point in time.</p><ul><li>If a successful callback is received you have to call <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/resume.html">resume(value: T)</a></li></ul><blockquote>Resumes the execution of the corresponding coroutine passing [value] as the return value of the last suspension point.</blockquote><ul><li>If an error occurs you need to call <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/resume-with-exception.html">resumeWithException(exception: Throwable)</a></li></ul><blockquote>Resumes the execution of the corresponding coroutine so that the [exception] is re-thrown right after the last suspension point.</blockquote><ul><li>We can cancel the execution of the coroutine by calling <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellable-continuation/cancel.html">cancellableContinuation.cancel</a><strong>()</strong></li></ul><blockquote>Cancels this continuation with an optional cancellation <em>cause</em>. The result is <em>true</em> if this continuation was cancelled as a result of this invocation, and <em>false</em> otherwise.</blockquote><p>I was using MVVM architecture and decided that the repository would have suspended functions only. Which can be further called from ViewModel in the viewModelScope. It worked great for the Room database and Retrofit library as they support coroutine out of the box.</p><p>I came across a scenario where I needed the location update. I have decided to write it in the repository as it is simply an input from another sensor in mobile devices. As per the standard practice, I was using <a href="https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient">FusedLocationAPI</a> to get the location details needed.</p><p>As per my rule, the repository will have only suspended functions. This constraint forced me to check for other alternatives and I came across this builder.</p><h3>Getting the last known location</h3><p>The first goal was to create a suspend function that can return the last known location of the device if it is available or will throw the appropriate error. <a href="https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient">FusedLocationAPI</a> provides a method <a href="https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#public-tasklocation-getlastlocation-">getLastLocation()</a> which will return the task containing either location or exception. We can add a complete listener to this task to observe the result.</p><p>To convert this callback-based function into the suspended function, I have used <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/suspend-cancellable-coroutine.html">SuspendCancellableCoroutine</a> as shown below.</p><pre>suspend fun getLastKnownLocation(): Location? {<br>    return suspendCancellableCoroutine { continuation -&gt;<br>        val flp = LocationServices.getFusedLocationProviderClient(context)<br>        val task = flp.lastLocation<br>        task.addOnCompleteListener {<br>            if (it.isSuccessful)<br>                continuation.resume(task.result)<br>            else<br>                continuation.resumeWithException(it.exception ?: NullPointerException())<br>        }<br>    }<br>}</pre><h3>Checking the GPS settings of the device</h3><p><a href="https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient">SettingAPI</a> must be accessed to ensure that the device’s system settings are properly configured for the app’s location needs. When requesting location services, the device’s system settings may be in a state that prevents an app from obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched off. This intent makes it easy to:</p><ul><li>Determine if the relevant system settings are enabled on the device to carry out the desired location request.</li><li>Optionally, invoke a dialog that allows the user to enable the necessary location settings with a single tap.</li></ul><p>To convert this into the suspended function, I have used the following code</p><pre>suspend fun checkLocationSettings(locationRequest: LocationRequest): LocationSettingResult {<br>    return suspendCancellableCoroutine { continuation -&gt;<br>        val builder = LocationSettingsRequest.Builder()<br>            .addLocationRequest(locationRequest)<br>        val client: SettingsClient = LocationServices.getSettingsClient(context)<br>        val task: Task&lt;LocationSettingsResponse&gt; = client.checkLocationSettings(builder.build())<br>        task.addOnSuccessListener {<br>            continuation.resume(LocationSettingResult(true))<br>        }<br>        task.addOnFailureListener {<br>            continuation.resume(LocationSettingResult(false, it))<br>        }<br>    }<br>}</pre><pre>data class LocationSettingResult(val success: Boolean, val error: Exception? = null)</pre><p>Here purposefully I am not calling the resumeWithException() method in failure callback because instead of abruptly canceling the execution, I want to show a location setting popup.</p><h3>Fetching continuous location updates</h3><p>As the last part of the use case, I want to get a continuous location update from <a href="https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient">FusedLocationAPI</a>. Before fetching the location updates I will check the location setting, if everything goes well I will start the updates.</p><pre>suspend fun getLocationUpdates(<br>    onLocationUpdated: (Pair&lt;Double, Double&gt;?, error: Exception?) -&gt; Unit) {<br>    return coroutineScope {<br>        val request = LocationRequest.create().apply {<br>            interval = 10000<br>            fastestInterval = 2000<br>            priority = LocationRequest.PRIORITY_HIGH_ACCURACY<br>        }<br><br>        val locationSettingsResult = checkLocationSettings(request)<br>        <br>        if (locationSettingsResult.success) {<br>            val done = CompletableDeferred&lt;Unit&gt;()<br>            val flp = LocationServices.getFusedLocationProviderClient(context)<br><br>            val callback = object : LocationCallback() {<br>                val mutex = Mutex()<br>                var job: Job? = null<br>                override fun onLocationResult(locationRestult: LocationResult?) {<br>                    locationRestult?.lastLocation?.let {<br>                        job?.cancel()<br>                        job = launch {<br>                            mutex.withLock {<br>                                onLocationUpdated(Pair(it.latitude, it.longitude), null)<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        try {<br>                flp.requestLocationUpdates(request, callback, Looper.getMainLooper())<br>                done.await()<br>            } finally {<br>                flp.removeLocationUpdates(callback)<br>            }<br>        } else {<br>            onLocationUpdated(null, locationSettingsResult.error)<br>        }<br>    }</pre><p>getLocationUpdates() function takes input as a lambda which will be called when either location or error is received. Let’s consider a scenario where the GPS setting is not appropriate, it needs to be turned on, and then getLocationUpdates() will get called with an exception. By calling the method mentioned in <a href="https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient">SettingsAPI</a> up for location enable can be shown.</p><p>On the other hand, if the GPS setting is appropriate then getLocationUpdates() will be called with Pair&lt;Double, Double&gt; containing latitude and longitude.</p><p>getLocationUpdates() function will get called from viewModelScope, so until the ViewModel is in memory location update will be delivered. The coroutine supports the structural concurrency due to which if the viewModelScope expires, it will throw the exception which will be caught by finally block and updates will be stopped. In this way, we can guarantee there is no memory leak happens during execution.</p><p>Using this builder function we can easily bridge the gap between callback-based and coroutine-based worlds. This will also work with any kind of Future, Task, Single, Maybe, etc. objects as they internally use the callbacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e345cb5f82e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globant/may-the-power-of-coroutine-be-with-you-e345cb5f82e1">May the power of Coroutine be with you…</a> was originally published in <a href="https://medium.com/globant">Globant</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture for mobile: To be, or not to be]]></title>
            <link>https://proandroiddev.com/clean-architecture-for-mobile-to-be-or-not-to-be-2ffc8d46e402?source=rss-d79f56c7947a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ffc8d46e402</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Gaurang Shaha]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 04:17:38 GMT</pubDate>
            <atom:updated>2023-12-10T18:01:50.583Z</atom:updated>
            <content:encoded><![CDATA[<p>As an Android developer, technology enthusiast, I’m always learning some new things which can help me in creating well organized, maintainable, and scalable codebase.</p><p>Recently I tried developing an entire application using the Clean Architecture, as the application is completed now I am taking a moment to analyze the impact of Clean Architecture. So let’s begin the journey of finding the answers for the question of the era, Clean Architecture: To be, or not to be 🤔</p><h4>Quick Overview: What is Clean Architecture?</h4><p>I have seen the <a href="https://www.youtube.com/watch?v=Nsjsiz2A9mg">videos</a> of our beloved Uncle Bob Martin several times just to understand the concept. Based on that, we can divide our entire system in the Domain, Data &amp; Presentation layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPhmO2dSf3nJwZ-GBbTr3Q.gif" /></figure><p><strong>Presentation Layer: </strong>This layer includes your activities, fragments and view model, etc. Mainly the UI related stuff.</p><p><strong>Data Layer: </strong>This layer includes your database, shared preferences, network calls, and location-related services, etc.</p><p><strong>Domain Layer: </strong>This includes use cases and entities. This layer has the entire business logic that resides in it. The entire application will evolve around this layer.</p><h4>Dependency Rule</h4><p>As you can see in the following diagram Presentation and Data layer will be always dependent on the Domain layer. The domain layer needs to be independent of the Presentation and Data layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxTZ2iWt186vCaQv74yGBw.png" /></figure><p>We can easily found the blogs explaining the pros of using Clean Architecture but there is so little to be said about the pitfall and constraints that it enforces. I will mainly focus on the pitfall and constraints of using the Clean Architecture, I hope it will help you make the correct choice of architecture.</p><p>Firstly, If you listen carefully to Uncle Bob’s talk, you will quickly realize that he suggesting us to apply Clean Architecture to the entire system i.e. back end and front end. Also, he says for UI layer use the MVP or MVVM architecture. Mobile applications that we develop is nothing but the UI for our systems.</p><p>Before opting for the Clean Architecture you must consider the following points to avoid the overhead of complexity and writing boilerplate code.</p><h4>Can we remove the domain layer or make it optional?</h4><p>I know a lot of eyebrows will be raised with this sentence. Generally, all the complex business logic is handled on the back end side. There is not much to handle on the front end, except some validation and simple mathematical calculations.</p><p>In the project I worked on, we have around 100 use cases, out of which 90 use cases just have a code for accessing the repository layer. The remaining 10 use cases are mostly for the validation data enter by the user in different forms. Also out of those 10 use cases no use case got reused.</p><p>Similar to our project, if the complex business logic handled by the server then you should give a serious thought of using MVP or MVVM kind of architecture. Clean Architecture in this type of project will demand you to create a lot of boilerplate code, use case, mapper, entity and test cases, etc. Writing those classes is error-prone and time-consuming.</p><p>Also, if your project has a strict deadline, people will find the shortcuts to achieve the functionality. I have seen the data entities used in the presentation layer, which will violets the dependency rule. Someone might argue that through code review should be done to avoid it, but when you have unrealistic targets and jobs on the line most ethical people will also choose the shortcuts. Please don’t miss considering the deadline while deciding on architecture.</p><p>For some projects, there might be some small amount of business logic which can be reused. In such cases even using MVP or MVVM we can create a common class for it, whether to call it use case or not is I will leave up to you.</p><p>By removing the domain layer I mean using MVP or MVVM and by making it optional I mean creating a class of reusable business logic.</p><h4>What about the dependency flow and separation of layers?</h4><p>While using MVVM or MVP, we can use the repository pattern which ensures the decoupling of data and UI layer. It will solve the issue of constantly changing APIs and structural modification in the database.</p><p>In my five year career, I have seen API changes more frequently than the UI. The API needs to provide support for various channels like mobile, web, etc. There are bound be some changes in the definition of API as we make progress. Aesthetic changes in UI will not require any change in the entity returned by the repository, the view layer can easily handle those.</p><p>So I can say that we can achieve the desired dependency flow and layer separation using MVP or MVVM.</p><h4>What about frameworks and third party libraries?</h4><p>You can say for certain that a piece of code that you’re not in control of will make your life harder. Generally, those are libraries and frameworks which we are using.</p><p>The library or framework creator constantly tries to update their library for adding new features and enhancing it. As a result of this, there will breaking changes along the way, which will force you to change the dependent code or in the worst case switch to another library due to compatibility issues.</p><p>To overcome this we can hide that dependency using a class or interface so that the change in the implementation of a single class will result in changes in the entire code base. This concept is a standalone thing, we can achieve it with any kind of architecture or even without any architecture.</p><p>While finding the candidates for this abstraction consider the frequency at which the library can change, the number of classes dependent on it, the amount of effort needed if there is some breaking change.</p><p>E.g. in one of my projects, we started using Retrofit 1.9, soon after Retrofit released 2.0. After updating the latest version everything got broken. We have to make the changes in almost all of the activities as there was no architecture in place. Such libraries with a wide range of reach in the codebase are the prime candidate for it. Similarly, we can abstract the library for loading images from the internet e.g. Glide, Picasso, etc.</p><p>On the other hand, I have used a library MPChart for displaying the charts. It is used only once in the entire application and that too in UI, so it doesn’t make any sense to abstract it.</p><h4>Will there be layers and boundaries?</h4><p>In MVP or MVVM, we can create data and presentation layers with ease. Even we can have a clear architectural boundary between them. If you are not having a large amount of business logic on the front end there is no need to have a domain layer. Two layers can suffice your need and can create a scalable application.</p><h4>Can we have a separation of concerns and responsibility?</h4><p>Separation of concern says that a component should have only one reason to change — one responsibility. Classes belonging to the database should have nothing to do with the UI or the networking components. They should be isolated. This can be easily achieved with MVP or MVVM and a repository pattern.</p><p>We can make the UI so dumb it should not contain application logic, but it will responsible for formatting, and make decisions on how to present them to the user. View Model or Presenter can help us with this.</p><h4>What about maintainability?</h4><p>I am considering mainly two factors under maintainability, ease of making changes &amp; adding new functionality. For the small project, where complex business logic is handled on the back end, you will find many duplicate entities. For each layer you create a separate entity, but under the hood, they are all similar. This will increase the size of the APK and the application’s memory footprint.</p><p>Making changes in such a project will have a larger impact as classes in different layer needs to be modified for a single change. This will be a repetitive and boring task. Even with MVP or MVVM, if proper care is taken we can structure our code is a way that we can easily add new functionality.</p><h4>What about testability?</h4><p>Using the mocking frameworks and testing library, we can make code written in MVP or MVVM architecture 100% testable. By mocking the behavior dependent classes we can decrease the execution time.</p><p>I am not saying that Clean Architecture is of no good for mobile application development. I am just trying to show another perspective.</p><p>Clean Architecture is not a silver bullet solution for all architectural needs. Do not get carried away by trends in the community when making the decision. For most projects MVP or MVVM is good enough to create a scalable and maintainable codebase.</p><p>You should decide based on the nature of your project. For example, if your project is big and complex, has a lot of business logic on the front end then Clean Architecture brings clear benefits.</p><p>On the other hand, for smaller and simpler projects, you will just end up writing more code and adding complexity with all the layers, investing more time along the way.</p><p>Let’s not make the cure worse than the disease. Take a wise decision considering the above points. I hope you will find them useful. If you feel I missed any point in the article, please do let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ffc8d46e402" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/clean-architecture-for-mobile-to-be-or-not-to-be-2ffc8d46e402">Clean Architecture for mobile: To be, or not to be</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>