<?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 Víctor Albertos on Medium]]></title>
        <description><![CDATA[Stories by Víctor Albertos on Medium]]></description>
        <link>https://medium.com/@victoralbertos?source=rss-ca56d10ba984------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MnYA0u3P0YpHHQ1a</url>
            <title>Stories by Víctor Albertos on Medium</title>
            <link>https://medium.com/@victoralbertos?source=rss-ca56d10ba984------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:13:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@victoralbertos/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[Let OpenAPI generate your Android network layer by leveraging Retrofit, Moshi, and Coroutines]]></title>
            <link>https://sourcediving.com/let-openapi-generate-your-android-network-layer-by-leveraging-retrofit-moshi-and-coroutines-aa0f86eba686?source=rss-ca56d10ba984------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0f86eba686</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Víctor Albertos]]></dc:creator>
            <pubDate>Tue, 10 Aug 2021 15:39:22 GMT</pubDate>
            <atom:updated>2021-08-10T15:52:07.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYmn5jSzSBJcTm9S4GIGEw.jpeg" /><figcaption><em>The Ten Commandments</em> (1923)</figcaption></figure><p>TLDR: By documenting the API with OpenAPI, we could automatically generate all the Moshi DTOs and the Retrofit Interfaces.</p><h4>Where we were</h4><p>Five years ago, the codebase of the Android Cookpad app did not even have different models to isolate the data mapping between layers: only massive objects casting their shadows through the entire stack.</p><p>When the resources allowed us to invest some time to improve this situation, we started by creating the DTOs that mapped the JSON responses from the server. With that, we set a clear separation between data boundaries and adjusted our representation to the actual data from the server. Nevertheless, the way we saw the data as clients was quite different from the view that the server had, leading to inefficiencies resulting from unreconciled views, namely indiscriminate nullability and abusive reusability of models that set the path to ambiguous abstractions.</p><h4>Where we wanted to be: OpenAPI as a way to establish an SSOT for the server and the clients</h4><p>A few months back, we decided to create clear contracts between the server and the clients as a cross-platform team effort. Both iOS and Android clients had declared nullability in their models as a defensive way to protect themselves from the lack of proper documentation of the consumed API. This capability to encode nullability as a semantic expression rather than a pathological fear, along with having a convenient way to document the API calls, was the main reason to finally decide to adopt a common tongue for all of us.</p><p>Henceforth, we decided to document the Cookpad API in a dedicated repository as an SSOT for Web, iOS, and Android engineers. Our tool of choice was the <a href="https://github.com/OAI/OpenAPI-Specification">OpenAPI-Specification</a>, as it has a community supporting it, and it seemed more mature.</p><h4>OpenAPI helped us to document the API but also to redesign parts of it.</h4><p><a href="https://swagger.io/specification/">OpenAPI works by writing schemas</a>, either on JSON or YAML files, that capture the structure of the data and the HTTP calls that expose them. Putting these schemas in place is meticulous work that requires the collaboration between the clients and the server, overlapping all those visions into one perspective that resembles some truth. Representative members of Web, iOS, and Android had extensive and productive discussions about how to document some specific pieces of data: should this attribute be marked as nullable? Should this endpoint be a PUT method instead of a PATCH? Should this model be reused and nested inside this other? Should this endpoint return an empty response?</p><p>The API started to make sense to us as we made collaborative improvements to shape the data structures and the endpoints used to expose them. We also discovered that a few endpoints were highly complex, subjecting the data structures of their responses to the supplied query parameters. This kind of endpoint, a harmful practice that can lead to obscure bugs, is almost impossible to document with the OpenAPI semantic constraints. The price you pay is adding lots of nullable properties to capture the plethora of data structures that endpoints can return.</p><p>The complexity boils down to reusing the same endpoint to fulfill different purposes, leading inevitably to the other painful practice when designing endpoints: <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">polymorphism</a>. This practice, which is helpful in other contexts, reveals itself here as a problem almost impossible to solve with the tools that OpenAPI offers. To make it compliant with the <a href="https://github.com/OpenAPITools/openapi-generator">openapi-generator</a>, and to be able to generate compilable sources, you will need to twist the OpenAPI semantics and add Regex-based Gradle tasks at the client-side to fine-tune the generated Retrofit endpoints and Moshi DTOs.</p><h4>A common workflow for the server and the clients.</h4><p>The way all engineers collaborate is through a common Github repository where we host all the OpenAPI schemas: when a feature needs to consume a new endpoint, or when a new property is deleted/updated, we change the docs accordingly to reflect this change, and the openapi-generator tool will re-generate at client-side the network layer with the latest changes. This workflow allows us to discuss the details of some specific endpoint beforehand, helping us shape a better interface for the clients considering the server specifications.</p><p>This practice encourages us to think more carefully about what changes could break the source compatibility and consider if old clients consuming previous API versions would support those new changes. We discover that we were pretty lenient in this regard and that more restrictive means were required to ensure backwards-compatible changes. We set a clear few rules about what we considered a breaking change and refined them based on an iterative process built of multiple situations. Once we identify a new change as a breaking change, it goes to the branch that represents the next API version. After that, clients need to prepare their codebase to accommodate those changes, starting a migration process that ensures the safety of the new API version adoption.</p><p>Each PR submitted to our OpenAPI repository requires passing multiple checks that guarantee compatibility with the existing serializers of the back-end implementation and the source compatibility for clients. These checks at both server-side and client-side make it easy to expose early the full impact of those changes by having a global picture of the new state of the API. Of course, these checks are still an ongoing effort that requires us to refine each new iteration with the code that brings us a unique situation. But the current state is mature enough to provide an effective workflow that seamlessly integrates the multiple collaborations between platforms.</p><h4>The Android goodies: generating the whole network layer using the documented schemas and OpenAPI.</h4><p>As if having documented all the data structures and endpoints of the API properly wasn’t enough reward, OpenAPI can create your entire network layer automatically as a bonus, including the DTOs and Retrofit interfaces. OpenAPI also offers <a href="https://openapi-generator.tech/docs/generators/kotlin/">various options</a> for serialization (Moshi, Gson, or Jackson) and asynchronous code execution (RxJava and Coroutines), probably covering most of your needs. This mechanism saves us the cost of manually creating the DTOs and endpoints and provides an automated way of upgrading the whole network layer to new technology. For example, to migrate from RxJava to Coroutines, you only need to re-run the Gradle task with the appropriate settings changed, and a brand new network layer will pop up in front of your eyes.</p><p>Indeed, a Gradle Plugin built on top of the openapi-generator makes the client code generation from the defined schemas a breeze. Running the specific Gradle task supplying a proper output config makes it possible to generate the source for iOS and Android clients fully adjusted to your current implementation. However, on Android, we needed to create an extra Gradle task that we execute on top of the generated sources to fine-tune them. For instance, documenting the headers in the OpenAPI schemas will add each one of them as a parameter to each Retrofit method-endpoint created by the openapi-generator. Since we already had OkHttp interceptors to supply them, we needed to make a Gradle task relying on Regex to remove all those arguments and avoid duplication.</p><p>We also noticed that not all the code created by the openapi-generator was helpful, as it was also generating the code required code to consume the HTTP calls and sometimes malformed DTOs that made our builds break. We also addressed that by using Gradle to cut the edges and make the generated code work for our needs. This decoupling between Moshi adapters, DTOs, Retrofit endpoint definitions, and the infrastructure code was very handy, allowing us to easily cherry-pick what we need to keep and discard the rest.</p><h4>A happy note</h4><p>OpenAPI made our API docs up to date and fully accessible for all the parties involved. It also forced us to rethink and redesign suboptimal/complex endpoints and data structures and create a contract set in stone that needs multiple hands to engrave new changes. We also used the very same stone to erect the Android network layer from our app, automatically generating the Retrofit interfaces and DTOs.</p><p>And last but not least, this collaborative effort between Web, iOS, and Android allowed us to reconcile our points of view about the API and know each other better as linked platforms, potentially making the following collaborations even smoother.</p><h4>A less happy note</h4><p>While rewarding in the end, adopting OpenAPI didn’t come for free. If you are planning to commit to this, here are some notes that could serve as warnings signs or shortcuts to make things smoother:</p><ul><li>Some complex endpoints, such as login/sign-up, or any crucial feature of your app for that matter, require to be carefully examined before being documented, and all the underlying complexity to be exposed “at compile time” to avoid devastating pitfalls “at runtime”. The role of QA here is essential.</li><li>Try to avoid polymorphic endpoints as much as possible. If that is not possible, consider using some automation (e.g. post-Gradle tasks) to make the code generated compilable and valuable for your context.</li><li>Rewriting the mappers to adjust the existing DTOs to the newly generated ones is where the bulk of the work takes place. This “chore” is the most challenging part and requires intense focus on the data structures to avoid missing mapping properties that are encoded slightly differently.</li><li>Starting from the easiest endpoints will speed up the learning curve, prepare you for more demanding endpoints whose complexity could overwhelm you, and address minor issues early.</li><li>DTOs duplication: the old manually created one and the new shiny DTO automatically generated will need to coexist during the migration period. If you want to avoid missing recent changes in any of them it’s paramount to have a proper channel to make the whole Android team aware of any change to the data structures as long as the migration phase is ongoing.</li><li>Whoever is going to tackle the migration requires a total commitment during several months. As an example, the Cookpad Android app took around three months to migrate its 143 endpoints.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0f86eba686" width="1" height="1" alt=""><hr><p><a href="https://sourcediving.com/let-openapi-generate-your-android-network-layer-by-leveraging-retrofit-moshi-and-coroutines-aa0f86eba686">Let OpenAPI generate your Android network layer by leveraging Retrofit, Moshi, and Coroutines</a> was originally published in <a href="https://sourcediving.com/">Source Diving</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CRUD operations with the new Android Paging v3]]></title>
            <link>https://sourcediving.com/crud-operations-with-the-new-android-paging-v3-5bf55110aa4d?source=rss-ca56d10ba984------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf55110aa4d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cookpad]]></category>
            <category><![CDATA[paging-library]]></category>
            <category><![CDATA[paging-v3]]></category>
            <dc:creator><![CDATA[Víctor Albertos]]></dc:creator>
            <pubDate>Tue, 24 Nov 2020 16:49:33 GMT</pubDate>
            <atom:updated>2020-11-24T16:49:33.931Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The source code companion can be found in this </em><a href="https://github.com/cookpad/android-crud-paging-v3"><em>Github repo </em></a><em>in the form of an Android app.</em></p><p>Even though the <a href="https://developer.android.com/topic/libraries/architecture/paging/v3-overview">new Paging v3</a> is still in alpha, it feels more mature than the v2 stable one: this last version is clearly the result of taking into consideration all the deficiencies that made using the previous version a painful experience, such as built-in adapters for both the paging itself and loading/error states, in-memory cache layer, and a granular updating of items without relying on Room.</p><p>The core components of the new API has been reduced to three: <em>androidx.paging.Pager</em>, <em>androidx.paging.PagingSource </em>and <em>androidx.paging.PagingDataAdapter</em>. Plus, these components are gracefully integrated between them and with the rest of the Jetpack components, for instance, <em>ViewModel</em> and <em>LiveData</em>.</p><p>There are several resources -including the <a href="https://developer.android.com/topic/libraries/architecture/paging/v3-overview">official docs</a>- already published about how to get started with the new v3 of the Paging library: <a href="https://medium.com/@fandygotama/paging-3-using-rxjava-3ddc218e4dba">this one</a> explains how to do it using Kotlin Coroutines, <a href="https://proandroiddev.com/how-to-use-the-paging-3-library-in-android-5d128bb5b1d8">another o</a>ne uses RxJava and leverages Room to provide a persistence layer. <strong>But</strong> <strong>the scope of the present post is sorely focused to perform </strong><a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete"><strong>CRUD operations</strong></a><strong> without using Room</strong>, <strong>specifically how to edit existing items, add new ones, and remove existing ones without invalidating the in-memory cache layer</strong>, just by making use of the operators that <em>androidx.paging.PagingData</em> exposes.</p><p>First of all, this is the model that will be shared across all layers to hold the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31bc82f3500ab12c09d8a40d8b31ed01/href">https://medium.com/media/31bc82f3500ab12c09d8a40d8b31ed01/href</a></iframe><p>This other model, <em>SampleViewEvents</em>, is used to communicate from the Fragment to the ViewModel the interactions with the UI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75d87ce035f82014f78770fbe9b6d4cd/href">https://medium.com/media/75d87ce035f82014f78770fbe9b6d4cd/href</a></iframe><p>Let’s continue by creating a repository to provide some mocked SampleEntity(s) making use of <a href="https://kotlinlang.org/docs/reference/coroutines-overview.html">Kotlin Coroutines</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e66f328a04c427ab86be932866795c7/href">https://medium.com/media/5e66f328a04c427ab86be932866795c7/href</a></iframe><p>We need now to extend from <em>PagingSource</em> to consume the repository and provide the logic to manage the index of the pages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68753179c09109034331e18c40fffdcb/href">https://medium.com/media/68753179c09109034331e18c40fffdcb/href</a></iframe><p>The <em>ViewModel</em> will use the <em>androidx.paging.Pager</em> and <em>SamplePagingSource</em> to instantiate a <em>LiveData&lt;PagingData&lt;SampleEntity&gt;&gt;</em> that will be retained with the proper lifecycle scope, and thus survive to <a href="https://developer.android.com/guide/topics/resources/runtime-changes+">Configurations changes</a>, showing always the latest state of the paginated list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29aa45ef0170a96b46d264e6d0e5f067/href">https://medium.com/media/29aa45ef0170a96b46d264e6d0e5f067/href</a></iframe><p>This <em>SampleViewModel</em> will also handle the <em>SampleViewEvents</em> logic required to perform the CRUD operations by relying on the proper <em>PagingData</em> methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7069da732120074798e51556fd25bd14/href">https://medium.com/media/7069da732120074798e51556fd25bd14/href</a></iframe><p><em>PagingData::filter</em> for Remove, <em>PagingData::map</em> for Edit, <em>PagingData::insertHeaderItem</em> for adding a new element at the top of the list, and finally <em>PagingData::InsertItemFooter</em> to add the new element to the bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PgS5asSSA6dyAfEjgmOLg.png" /><figcaption>Read — Create — Update — Delete</figcaption></figure><p>We also need an <em>Adapter</em> that extends from <em>PagingDataAdapter</em> and binds the <em>ViewModel</em> with the view interactions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b064a472d488eb67e2d7d94d8412de4d/href">https://medium.com/media/b064a472d488eb67e2d7d94d8412de4d/href</a></iframe><p>Finally, this <em>Fragment</em> will observe the <em>SampleViewModel::pagingDataViewStates</em> to submit the new data to the <em>Adapter</em> and bind the UI actions to each <em>SampleViewEvents</em> which is conveniently pushed to the <em>ViewModel</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4613254505fbfa59caf0c10a50946fee/href">https://medium.com/media/4613254505fbfa59caf0c10a50946fee/href</a></iframe><p>And that’s all that you need to implement an updatable paginated list with the new Paging version: which is quite awesome considering that the author of this post was not even able to explain to himself how he managed to do it in the previous Paging version.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf55110aa4d" width="1" height="1" alt=""><hr><p><a href="https://sourcediving.com/crud-operations-with-the-new-android-paging-v3-5bf55110aa4d">CRUD operations with the new Android Paging v3</a> was originally published in <a href="https://sourcediving.com/">Source Diving</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy debugging with the Android Navigation component]]></title>
            <link>https://sourcediving.com/easy-debugging-with-the-android-navigation-component-89a6c7cafab8?source=rss-ca56d10ba984------2</link>
            <guid isPermaLink="false">https://medium.com/p/89a6c7cafab8</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cookpad]]></category>
            <category><![CDATA[navigation-component]]></category>
            <dc:creator><![CDATA[Víctor Albertos]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 11:07:22 GMT</pubDate>
            <atom:updated>2020-09-22T11:07:22.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqr_NJcmDQEdboEK3UoBpA.jpeg" /><figcaption><a href="https://pixabay.com/photos/compass-map-retro-geography-5137269/">https://pixabay.com/photos/compass-map-retro-geography-5137269/</a></figcaption></figure><p>It’s handy to be able to <strong>log the navigation path </strong>of the users and make its rendering layer dependant on the build type.</p><p><strong>For debug builds</strong>, during development, printing the navigation flow to the Android <em>logcat</em> can help to get familiar with the relations between fragments and screens: sometimes it is not easy to link a view with its component representation, as for big apps, the teams don’t usually know the details of the implementation of each screen.</p><p><strong>For release builds</strong>, when a crash is reported on production, having the navigation path alongside the <em>stacktrace</em> can help to spot quicker what’s the cause of the bug. In <a href="https://sourcediving.com/">Cookpad</a> we use <a href="https://firebase.google.com/products/crashlytics">Crashlytics</a>, which makes it pretty easy to send the information and attach it to the right user session:</p><pre>FirebaseCrashlytics.getInstance().log(destinationData.toString())</pre><p><strong>Creating a mechanism for logging the navigational flow </strong>is quite easy if you use the <a href="https://developer.android.com/guide/navigation">Android Navigation component</a>. In the <a href="https://play.google.com/store/apps/details?id=com.mufumbo.android.recipe.search&amp;hl=en">Cookpad Android app</a>, we have a class called <em>NavTracker</em> which implements <em>NavController.OnDestinationChangedListener</em> and it is in charge of extracting all the relevant data of the current destination and its associated <em>Bundle</em>.</p><p>It has <em>NavTrackerLog</em> as a dependency that hides the layer in which the data is printed out making it that way build-dependant. Thus, this interface is conveniently implemented in the release build with the Crashlytics call shown before and in the debug build as follows:</p><pre>NavTrackerLogDebug<strong> </strong>: NavTrackerLog {<br>    <strong>override fun </strong>log(destinationData: JSONObject) {<br>        Log.d(NavTracker::<strong>class</strong>.<strong>simpleName</strong>, destinationData.toString())<br>    }<br>}</pre><p>And this is the NavTracker class:</p><pre>class NavTracker(private val context: Context, private val navTrackerLog: NavTrackerLog) :<br>    NavController.OnDestinationChangedListener {</pre><pre>override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {<br>        val res = context.resources<br>        navTrackerLog.log(<br>            JSONObject()<br>                .put(&quot;destination&quot;, res.getResourceEntryName(destination.id))<br>                .put(&quot;startDestination&quot;, res.getResourceEntryName(controller.graph.startDestination))<br>                .put(&quot;bundleJsonData&quot;, bundleToJson(arguments ?: Bundle()))<br>        )<br>    }</pre><pre>private fun bundleToJson(bundle: Bundle) = JSONObject()<br>        .apply {<br>            bundle.keySet().forEach { key -&gt;<br>                put(key, JSONObject.wrap(bundle.get(key)))<br>            }<br>        }<br>}</pre><p>As the last step, <em>NavTracker</em> is set to all the available <em>NavController</em>(s), by calling <em>addOnDestinationChangedListener</em> on them and supplying the instance of <em>NavTracker</em>:</p><pre>findNavController(R.id.your_nav_host_fragment).addOnDestinationChangedListener(navTracker)</pre><p><strong>This is the result</strong> of a navigational path consisting of three screens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*39vFEMmz1nwWSS8VUovYaw.png" /><figcaption>feed, recipe detail, and user profile</figcaption></figure><p>Android Logcat output:</p><pre>{<br>   &quot;destination&quot;:&quot;feedTabFragment&quot;,<br>   &quot;startDestination&quot;:&quot;feedTabFragment&quot;,<br>   &quot;bundleJsonData&quot;:{<br>      <br>   }<br>}</pre><pre>{<br>   &quot;destination&quot;:&quot;recipeViewFragment&quot;,<br>   &quot;startDestination&quot;:&quot;feedTabFragment&quot;,<br>   &quot;bundleJsonData&quot;:{<br>      &quot;showTranslatedRecipe&quot;:false,<br>      &quot;recipe&quot;:null,<br>      &quot;recipeId&quot;:&quot;4042&quot;,<br>      &quot;deepLinkUri&quot;:null,<br>      &quot;deepLinkVia&quot;:null,<br>      &quot;isDeepLink&quot;:false,<br>      &quot;isLaunchForEditsRestore&quot;:false<br>   }<br>}</pre><pre>{<br>   &quot;destination&quot;:&quot;userProfileFragment&quot;,<br>   &quot;startDestination&quot;:&quot;feedTabFragment&quot;,<br>   &quot;bundleJsonData&quot;:{<br>      &quot;userId&quot;:&quot;38&quot;,<br>      &quot;deepLinkUri&quot;:null,<br>      &quot;showTranslatedProfile&quot;:false,<br>      &quot;scrollToRecipes&quot;:false<br>   }<br>}</pre><p>Firebase console output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*di4vWBy7s4Pf9d4b80BRiA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89a6c7cafab8" width="1" height="1" alt=""><hr><p><a href="https://sourcediving.com/easy-debugging-with-the-android-navigation-component-89a6c7cafab8">Easy debugging with the Android Navigation component</a> was originally published in <a href="https://sourcediving.com/">Source Diving</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating towards a new navigation]]></title>
            <link>https://sourcediving.com/navigating-towards-a-new-navigation-154011622435?source=rss-ca56d10ba984------2</link>
            <guid isPermaLink="false">https://medium.com/p/154011622435</guid>
            <category><![CDATA[navigation-component]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cookpad]]></category>
            <dc:creator><![CDATA[Víctor Albertos]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:33:59 GMT</pubDate>
            <atom:updated>2020-08-05T08:33:59.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJaH6qUVSyZ2cW6evuHcWg.jpeg" /><figcaption><a href="https://pixabay.com/photos/boat-storm-rain-raining-vessel-962791/">https://pixabay.com/photos/boat-storm-rain-raining-vessel-962791/</a></figcaption></figure><p><strong>TLDR: </strong>We migrated our code-base to the Navigation component and we are happy now, even though we weren’t during most of the migration process.</p><h3>We decide to migrate to the Navigation component</h3><p>The Cookpad Android team decided to migrate to the <a href="https://developer.android.com/guide/navigation/navigation-getting-started">Jetpack Navigation component</a>. We want to share here our experience of the migration itself rather than a tutorial about how we did it because the way we did it was simply by following the <a href="https://developer.android.com/guide/navigation/navigation-migrate">official docs</a>. To be clear: this is not about how can you work out the migration but rather how the migration will <em>work</em> you.</p><p>We wanted to migrate to the Navigation component to replace homemade workarounds by an official-standard solution, those were components used for navigating between screens declared in a multi-module project setup. Most of our screens were Activities and to navigate between them we started Intents with the proper setup in each case. With the purpose to move forward on Google expectations, we decided to switch to Fragments and the Navigation component to handle the navigation between them. But we had a few concerns that prevented us from making the decision:</p><ul><li>Product required to preserve the back stack in each tab of the <a href="https://material.io/components/bottom-navigation">bottom navigation bar</a>, and this feature was not available as part of the Navigation library. Luckily, Google had in its navigation sample code repository<a href="https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample"> a showcase called NavigationAdvancedSample </a>which illustrates how to support a multiple back stack. Unfortunately, it was quite limited as it did not take into account the complexities of a production app, so we couldn’t trust that using it out of the box would work for us.</li><li>We never were big fans of Fragments and the Navigation component expects you to use them, intensively, almost exclusively; but in return, the library offers a new API that makes using them feel that they are just normal pieces of software that draw thigs on the screen: you don’t need to commit awful transactions with some manager to go to the next screen. Plus, it seems nowadays fragments are the new activities and the actual activities are the Android app.</li></ul><p>So we decided that taking that risk was worth it considering all the potential benefits, mainly: replacing a custom solution by a standard way of navigating. We were capable of foreseeing the main issues but not their major ramifications, which was good enough considering that we never wanted to see way beyond to avoid losing the motivation that made us start. Knowing too much too soon would have prevented us from knowing this much now and you from reading this post (which could be perfectly fine on the other hand).</p><h3>We navigate to a shipwreck as the destination itself</h3><p>Don’t fight the framework, let the framework fight itself. If the library expects from you to do B, and in order to do B you first need to do A, but the library does not allow you to do A (right, yeah?), then find a way to let believe the library that you did A. Do as the library tells you except in those cases where contradicting its instructions will make your compliance with further, more relevant instructions. Let’s narrow this idea to a concrete example: to pass data between screens, the library advises to use <a href="https://developer.android.com/guide/navigation/navigation-pass-data">SafeArgs</a>, this is ideal as it does compile-time checks to avoid launching screens without the proper parameters. But in order to be able to do this without adding a complexity that would make the usage of SafeArgs not worth it, you need to keep one single navigation graph for your entire application. Why? Here we go:</p><ul><li>The arguments declared in the destination of another graph need to be copy/pasted into the action that points to that destination. This leads to huge duplications of code and also opens the door to dangerous situations: if you add a new argument to the destination and forget to update all the actions that point to that destination (and there are always more screens in your app than you think), the app will crash at runtime and the SafeArgs plugin will not be longer “safe”.</li><li>Global actions can not be shared between graphs, which means that any screen accessing another screen that is not declared in the same graph requires to rewrite its associated action. This issue, in conjunction with the previous one, guarantees massive code duplication.</li><li>When calling a graph from another graph, it is not possible to select the entry point (the screen that we want to launch), we can only use the one annotated as such in the destination graph.</li></ul><p>You can’t follow the official stance of using multiple graphs on top of SafeArgs and at the same time follow the basic rules of common sense. But of course, we needed to pay for this one single graph, even if the API of the library became easier due to the concept of the graph was no longer present in the way we created and consumed destinations.</p><h3>We decide to have one single navigation graph and we pay for it</h3><p>The sample code that Google provides to showcase how to create a bottom navigation bar with multiple back stacks requires to have different graphs for each tab, otherwise when launching the app via <a href="https://developer.android.com/guide/navigation/navigation-deep-link">explicit deep links</a> either the app will crash or it will duplicate the deep link destination for each one of the tabs (depending on the version of the library). To solve this issue, we needed to hack the hack that Google provided, and we thought that the result was useful enough to promote it to an Android library: <a href="https://github.com/cookpad/BottomNavWatson">BottomNavWatson</a>, named Watson after the legendary <a href="http://actionbarsherlock.com/">ActionBarSherlock</a>, as it is in the bottom the same way Sherlock is above Watson. This library allows, when using the <a href="https://developer.android.com/reference/com/google/android/material/bottomnavigation/BottomNavigationView">BottomNavigationView</a>, to use the multiple back stack workaround provided on Google Samples with one single navigation graph per application.</p><p>That was the main ramification of the issue of using multiple back stacks. But the interesting thing is the chain reaction that led to the specific scenario where we needed to create the Watson library, or rather the underlying mindset: always conform with the contract of the library, even if it means leveraging some loopholes to fully conform in the crucial points.</p><h3>We must accept that the views we don’t see no longer exist</h3><p>The other significant ramification was related to fragments. The documentation of the library is missing a crucial piece of information, especially <a href="https://developer.android.com/guide/navigation/navigation-migrate">the docs which are dedicated to guiding the migration</a>: when navigating back to the previous screen its view will be always (re)created. This is neither the same as a <a href="https://medium.com/inloopx/android-process-kill-and-the-big-implications-for-your-app-1ecbed4921cb">process death</a> nor a <a href="https://developer.android.com/guide/topics/resources/runtime-changes">config change</a>, in those cases, the view is destroyed but also the fragment, and in the latter, only the ViewModel survives, however in this new case the fragment is retained and only its view destroyed. This wasn’t a familiar screen state for us, and thus we did not have our screens prepared for that. The fragment’s properties aren’t re-created in this state but still its view is re-created, and this could lead to subtle bugs for components like the <a href="https://developer.android.com/reference/android/arch/paging/PagedListAdapter">PagedListAdapter</a> and the <a href="https://developer.android.com/topic/libraries/architecture/paging">Paginator</a>.</p><p>But saying that the view is recreated implies that it has to be destroyed at some point, and that happens every time that the view goes to the background. Indeed, another major issue that we faced was updating the views of screens that were on the background using a <a href="https://github.com/cookpad/ViewsWaiter">reactive pipeline</a> (kind of an Rx event bus). When using activities to navigate between screens, the view is retained in the background and it is possible to update it meanwhile the screen is on the background, but with this new state we needed to rethink and change the whole process: the view could no longer be updated in place, right away, the emission from the pipeline had to be deferred until the view was again re-created, and for that purpose, we used a LiveData stream whose subscription was properly tied to the lifecycle of the view. Migrating to the nav library made one latent issue become quite obvious: careless lifecycle management for view (re)creations leads to inconsistent screen states. In this sense, migrating to the nav library made bad things worse, up to a point where we needed to fix them.</p><h3>We’re happy with the migration overall, but not as much as we’re with it being finished</h3><p>The major benefits that we had with the migration can be summarised as follow:</p><ul><li>Being able to replace our own abstractions to navigate between screens declared in different Gradle modules by a standard solution which any developer will be familiar with.</li><li>Exposing latent issues with the way we handled the lifecycle of the views that were generating memory leaks.</li><li>Using SafeArgs to ensure at compile time that we’re launching each screen with the required parameters.</li><li>Get rid of the boilerplate required to provide unique entry points for launching screens.</li><li>A handy API to build PendingIntent(s) to provide screen destinations for push notifications and deep links.</li></ul><h3>Some considerations when migrating to the Navigation component</h3><ul><li>Always prefer using the <em>Fragment::viewLifecycleOwner</em> to subscribe to LiveData streams inside the <em>Fragment::onViewCreated</em> callback.</li><li>Always remember to dispose resources/fields that may contain View/Context references and outlive the View on the onDestroyView callback (e.g.: adapters, tab mediators, view delegates, etc).</li><li>Always delegate View state to ViewModel and LiveDatas in order to be able to restore the screen state after re-creation.</li><li>Do not use any event bus solution on Fragments, always prefer to subscribe to them on ViewModel, and expose its events using LiveData. This will avoid crashes/misbehavior when the pipeline emits a value and the Fragment’s view is destroyed.</li><li>Don’t use lazy initialization when storing RxBindings for View events, as this is a potential cause of leaks. Prefer using a get() accessor or just subscribe to it inside <em>Fragment::onViewCreated</em> callback.</li><li>PagedListAdapter(s) need to bind to a proper lifecycle every time that the view is recreated, without that the Paginator(s) will start to misbehave.</li></ul><h3><strong>A consideration before migrating to the Navigation component</strong></h3><p>If your team doesn’t have enough resources to invest in this migration maybe it’s not a good idea to start it. We had allocated two members of the Android team (<a href="https://medium.com/u/7aa4b6ffa25">Felipe Augusto Pedroso</a> 👋 and myself) fully focused on this task for about three months. Only a part of the issues that we had to face were actual navigation issues, the others were side effects of a new navigation system which changes the lifecycle of the screens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=154011622435" width="1" height="1" alt=""><hr><p><a href="https://sourcediving.com/navigating-towards-a-new-navigation-154011622435">Navigating towards a new navigation</a> was originally published in <a href="https://sourcediving.com/">Source Diving</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin adoption on the Android open source community]]></title>
            <link>https://medium.com/@victoralbertos/kotlin-adoption-on-the-android-open-source-community-fe01d00a8bb3?source=rss-ca56d10ba984------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe01d00a8bb3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Víctor Albertos]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 16:43:59 GMT</pubDate>
            <atom:updated>2019-01-23T19:23:58.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bj0LBmnJY-Kq5dYC5amo4w.jpeg" /><figcaption>Thanks <a href="http://twitter.com/pabloppp">@pabloppp</a> for his amazing casual style</figcaption></figure><p>It’s well known how much <a href="https://insights.stackoverflow.com/survey/2018/#most-loved-dreaded-and-wanted">Android developers claim to love Kotlin</a>. But as love is not satisfied with words, -and because I had to write a post for a <a href="https://eu.udacity.com/course/data-scientist-nanodegree--nd025">data scientist course</a> (you’re welcome Udacity), I thought to gather some evidence to verify that claim.</p><p>How? By evaluating <strong>the adoption of Kotlin on the Android open source community </strong>(I mean Github). To do so, we’ll address several points relying on descriptive analyses to put the matter in perspective. The raw data to build the datasets has been gathered from <a href="https://developer.github.com/v4/">GitHub GraphQL API v4</a>. As you may expect, <strong>expect all kind of bugs and inaccurate interpretations. </strong>But this is a happy place, for data disclaimers and other sad considerations refer to the backing <a href="https://github.com/VictorAlbertos/android-kotlin-adoption">Github repository</a>.</p><h3>Kotlin vs Java Android repositories created on Github</h3><p>Let’s first take a look at the number of Android repositories whose main language is Kotlin that have been created since <a href="https://en.wikipedia.org/wiki/Kotlin_(programming_language)#History">Kotlin 1.0 (the first officially stable release)</a> was publised at 2016–02–15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*uVTYQi4dnZbmQ1pA28Z6fA.png" /><figcaption>Monthly Android Kotlin repositories created from 2016–02–15 to 2019–01–15</figcaption></figure><p>Every dot in the plot shows the number of Android Kotlin repositories created during a month. <strong>In the last month, about 1,900 Kotlin repositories were created.</strong> Are these numbers high? I couldn’t tell, what I can tell is that<strong> there is a steady increasing trend.</strong></p><p>To know if these numbers represent a significant part of the Android open source community <strong>we have to compare them</strong>. By making them relative to some terms, we get a sense of their impact in the scope represented by those terms. The scope is formed by two terms: 1) <strong>Kotlin vs Java within the Android community </strong>to know in what degree Kotlin has been adopted by the Android community<strong> </strong>and 2)<strong> Kotlin vs Java outside the Android community</strong> to know if the ratio of adoption within the Android community is relevant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*5jw755yQW5L-_FYSS-974Q.png" /><figcaption>Monthly ratio of repositories created from 2016–02–15 to 2019–01–15</figcaption></figure><p>The green line represents the ratio between the Kotlin vs Java repositories created in a monthly bases within the Android community. The blue one represents the same relationship but outside the Android ecosystem -meaning all those Kotlin and Java repositories not related with Android. <strong>We observe in both cases a steady increasing trend, but in the case of Android repositories is 3 times bigger.</strong> Namely,<strong> the last month shows a 16% of Android Kotlin repositories compared with the 4.3% of Kotlin not Android repositories.</strong></p><p>It seems that there is a big difference. But does this difference mean that Android developers love Kotlin more than common Java ones? I don’t think so. I think that common Java developers hate less Java because they are not stuck with the same language version that they used to create their scholar projects in Netbeans.</p><p>Also because of the following fact.</p><h3>Google made Kotlin an official programming language for Android development</h3><p>You may have noticed that on May 17, 2017, there was a huge pike on the percentage of Kotlin repositories. Let’s highlight that date:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*ZH06T_ZQ3yQWzjqZJwT8vQ.png" /></figure><p>During an unbearable time, Android developers had to keep their love in secret. But it was during the <a href="https://events.google.com/io2017/">Google I/O 2017 </a>that an announcement made from Google changed the whole vaudeville picture: a parent’s blessing in marriage, by which Android developers were now allowed to fulfill their true love for Kotlin.</p><p>And they did it. <strong>The month in which the statement was made the percentage of repositories created with Kotlin increased to 6.3%. </strong>Having the previous month a percentage of 2.4%, we can infer the huge impact that that blessing had. And the effect was not limited to that specific month, but rather it kept affecting subsequent months until the present day.</p><p>What motivations are behind Google’s decision is something beyond my resources and interest. One thing is clear though: this parent allows polygamy because Java has not been (yet) expelled from the marriage.</p><h3>Kotlin Android repositories migrated from Java on Github</h3><p>To almost complete this incomplete analysis, I think it would be worth knowing how many active repositories have migrated from Java since Kotlin was release.</p><p>As it has been said before, you can refer to the <a href="https://github.com/VictorAlbertos/android-kotlin-adoption">backing Github repository</a> for implementation details about the dataset creation. That being said, a repository is considered to be migrated if it was created before the first stable Kotlin 1.0 release date and its main language nowadays is Kotlin.</p><p><strong>Data shows that 8.6% of the repositories were migrated to Kotlin. Comparing this ratio with the percentage of Kotlin repositories created during the whole historical, 6.9%, we can observe that both ratios show a similar pace.</strong> It seems that Android developers are not only willing to use Kotlin for brand new projects, but also for those which are already a valuable contribution to the community.</p><p>Another interesting (?) question is if the migrated repositories share some common features. Let’s draw a table showing the mean for several attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZ-sV9g4MEpF4VRmzvNO2g.png" /><figcaption>Attribute averages grouping by Kotlin migrated and Java repositories</figcaption></figure><p>Having in mind that the dataset distribution for migrated vs not migrated repositories is not symmetric (kotlin: 78 vs java: 833), we can try to formulate some thoughts about their compositions.</p><p><strong>Kotlin migrated repositories seems to be slightly more popular, showing higher mean for the number of forks (kotlin: 324 vs. java: 256), watchers (kotlin: 72 vs. java: 67) and starts (kotlin: 1192 vs. java: 943).</strong> It goes along with the previous trends where we saw how the percentage of repositories created with Kotlin was increasing almost constantly in a monthly bases.</p><p>On the other hand, <strong>Java not migrated repositories tends to be “bigger”, having a greater size on disk (kotlin: 26MB vs. java: 78MB) as such as a more number of pull requests (kotlin: 96 vs. java: 117). </strong>This makes sense because of the amount of time invested is higher to migrate bigger projects (probably meaning larger code bases).</p><p>As a last step, let’s just draw a correlation heatmap to see if there are relationships with the target feature “migrated”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*sm4Mjt9YFltzJv3V5iveCg.png" /></figure><p>The correlation heatmap shows very low coefficients but the direction of their relationships points out to the same conclusion drawn when inspecting the means: <strong>the projects migrated to Kotlin are more popular and less big than those which did not migrate.</strong></p><h3>Should I move to Kotlin?</h3><p>We’re already doing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe01d00a8bb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A tragic tale about people having fun modularizing things that were no longer an Android app]]></title>
            <link>https://sourcediving.com/a-tragic-tale-about-people-having-fun-modularizing-things-that-were-no-longer-an-android-app-3451afed898f?source=rss-ca56d10ba984------2</link>
            <guid isPermaLink="false">https://medium.com/p/3451afed898f</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[modularizing]]></category>
            <dc:creator><![CDATA[Víctor Albertos]]></dc:creator>
            <pubDate>Mon, 18 Jun 2018 07:35:41 GMT</pubDate>
            <atom:updated>2018-07-05T10:51:08.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Six months ago, in the Cookpad Android team, we made the -right?, wrong?, tough!- decision to migrate from a monolithic module setup to a multi-module one (of course there was blood, as you may expect from any argument between highly educated people). This is a tale of pain, plus an anecdote about how Cookpad Ltd. (“Make everyday cooking fun!”) became StringPatchers lib (“an android lib for updating string resources on the fly”). Wait for it, we keep the anecdote for the end of the post because we really believe that’s the only reason why you’ll keep reading on.</p><h3>1. Modularizing, why?</h3><h4>A team is an API</h4><p>We thought that a modularized architecture would allow us to be more productive by reflecting our organizational structure, based on squads -a fancy way of saying that we are organized in small teams with a product oriented goal.</p><p>Our Android team is currently growing very fast (<a href="https://www.workable.com/j/D81FDBE1E9">Cookpad wants you!</a>), so we needed a clear separation of concerns based on the very constitution of our product, rather than on technical layers. That way a developer who’s working on -let’s say- the Onboarding section doesn’t need to worry about the internals of Chat section, and at the end our team would share responsibilities like any other fine tuned API.</p><p>When things get bigger and bigger (the code, the teams, etc) the best way to handle their complexity is by specializing and distributing responsibilities (or for that matter, exposing APIs). It’s easier to maintain 10 small but well defined libraries than a big messy one, and the same goes for any code base.</p><h4>Lean software development</h4><p>At Cookpad we are always iterating over the product, always shipping new features with the hope of improving the user experience.</p><p>What we do -that some people like to call Lean Software Development or LSD- is achieved by performing experiments: we release a feature, introduce several bugs, release a hotfix, introduce more bugs, release a new hotfix, perform analysis relying on metrics and iterate.</p><p>When we have a feature-separated module structure, code conflicts can also be greatly minimized. For example, changing code in “Search” module, will have zero impact on the “Chat” module. Also, this isolation encourages experimenting with brand new technologies, for instance, we can experiment with Google architectural components without spreading the ideological infection to all the members at once.</p><h4>Reducing build time (more a hope than a fact at this time)</h4><p>When a team wants to develop new features as fast as possible, a long build time is a complete burden. Cookpad’s (main and only) module was full of code, like Gargantua that eats non-stop but also eats transitively, and because we could not put it on diet, we put it to death.</p><p>We were hoping that by reducing it to small pieces the time it took for processing will be less. Now we know that our hope will become real eventually. It means that we need our code base to get (even) bigger to see a significant benefit on build time.</p><h3>2. Modularizing, how?</h3><p>Our next step was getting as much information as possible on how to modularize, so we researched hoping that “state of art” would be something more than a pedantic expression for referring the “current state”.</p><p>Sadly it was not.</p><p>We did not find any documented experience about migrating an entire code base from a monolithic setup to a multi-module one. Neither this article has such an aspiration. That’s actually why/how we’re writing this post, as a therapy, to expose (and even proclaim) our pain. Thus, we make our public statement not to teach some lesson, but to learn something from the feedback that we might, eventually (please, please) get.</p><p>So there we were, with no plan whatsoever rather than an optimistic (by simplistic) conceptual-map about where we wanted to go. The picture was very easy to draw but very hard to understand. Circles (modules) and lines (relationships) convoluting altogether, showing a dependency graph as a big big warning: “don’t touch me if you don’t love me!”. We were not completely aware -at that time- that the picture did not reflect the complexity of the actual implementation -like any other UML diagram, you truly get it only by the end of its implementation.</p><p>We were aware of our own limitations and therefore knew that something that’s too brilliant tends to make you go blind. Are you familiar with “the wrong abstraction”?</p><p>We are, we truly are. It happens when you think you are more clever than you actually are and makes others confused (and yourself too after a few commits). Now, take that wrong abstraction and embrace it to an structural level; you don’t get any more a Picasso painting, what you get is Picasso’s mindset as the foundation of your code base. And because programming is not art, or it is the non-art of avoiding subjectivity at any cost, what was supposed to be a boring thing -the foundation of your code, a common ground for next engineers to landing peacefully- is now the expression of the struggling in your own confusion… and that resemblences art.</p><p>That was one of our major fears: blending an intricate graph of dependencies between modules to resolve their external components. So, we decided to really take care of indirections by making them as simple as possible.</p><p>There were two ways for resolving dependencies: either the module asks for it explicitly, or another module is extracted out containing that dependency and added to the first one as a compilation dependency. We tried to balance it: with some components it made sense isolating them into a compilation unit and exposing it as a library, such as logger or debugger; but with other dependencies (screens beyond the scope of the module) requesting them by exposing an interface was the most sensible thing to do.</p><p>For the first case (module asks for dependencies) we did not use Dagger because the project was five years old and five years old means five years of legacy code. Also, Dagger could help us to hide some of the internals for exposing and resolving dependencies with a clever and subtle API, but we wanted the opposite, we wanted to make this as ugly as possible by revealing the dependencies of our code debt. That’s right, by modularizing your project you get the chance to open a wonderful present. But remember, remember, remember: “Sir, what you will see… you will not be able to unsee.”</p><p>We never intended to implement a platonic representation of our code base. Trying to achieve that degree of granularity and decoupling would have lead us to “the wrong abstraction”. The reaction that we aimed for was simple: “This is as ugly as stupid. Now that I know how to use it, let me improve it.” How did we achieve that? Kotlin did the job for us.</p><p>Inside a module, let’s call it “recipe”, an interface declaring all its dependencies is exposed to the outer world. This interface is implemented by an `Object` using delegation, and the instance is initialized by the outer world.</p><pre>var recipeModule: RecipeModule? = null</pre><pre>interface RecipeModule {<br>    fun launchChatActivityWithChat(activity: Activity, chat: Chat)<br>    fun launchHomeActivity(context: Context, shouldSwitchToFirstTab: Boolean)<br>    /**<br>     * More, much more code!<br>     */<br>}</pre><pre>object RecipeComponent : RecipeModule by recipeModule!!</pre><p>Any component inside “recipe” module would access external dependencies thought that “RecipeComponent” `Object`.</p><pre>RecipeComponent.launchChatActivityWithChat(activity, chat)</pre><p>Now, the outer world is the entry point of the app. The only module which is an android application and depends on the rest of the modules. The implementation of “RecipeModule” interface lays down in this glue module:</p><pre>object RecipeModuleImplementation : RecipeModule {</pre><pre>    override fun launchChatActivityWithChat(activity: Activity, chat: Chat) {<br>        ChatActivity.launchWithChat(activity, chat)<br>    }</pre><pre>    override fun launchHomeActivity(context: Context, shouldSwitchToFirstTab: Boolean) {<br>        HomeActivity.launch(context, shouldSwitchToFirstTab = shouldSwitchToFirstTab)<br>    }<br>    /**<br>     * More, much more code!<br>     */<br>}</pre><p>Last part, initialize that “recipeModule” instance to avoid `NullPointerException` (that’s one of the things that makes this so ugly but so convenient). When? Upfront. And <em>when</em> leads to <em>where</em>: In the android application `onCreate call`, of course!</p><pre>/**<br> * More, much more code!<br> */<br>class CookpadApplication : Application(), CookpadApp {<br>    /**<br>     * More, much more code!<br>     */<br>    <br>    override fun onCreate() {<br>        super.onCreate()<br>        setupModules()<br>        /**<br>         * More, much more code!<br>         */<br>    }<br>    /**    * ¡ǝpoɔ ǝɹoɯ ɥɔnɯ &#39;ǝɹoɯ<br>   */<br>    private fun setupModules() {<br>        recipeModule = RecipeModuleImplementation<br>        /**<br>         * More, much more code!<br>         */<br>    }<br>    /**<br>     * More, much more code!<br>     */<br>}<br>/**<br> * More, much more code!<br> */</pre><p>Determining the shape of your puzzle and how you are going to put its pieces together is the funny part of this process. After knowing how many modules and how to resolve their dependencies, what follows it’s just a matter of moving things around. Let us describe how was the process in our daily bases, we guarantee that it felt like a bash script written during some internship for a task that nobody cared.</p><blockquote>Oh look!! it’s only one Activiy, that’s easy to move, oh no wait it has a fragment inside, but… it also has an adapter, oh and 10 view holders, and every view holder holds 2 custom views, and for any of this Java/Kotlin components (yes!, we were migrating all at the same time), I have to move an xml resource, well at least it’s just one layout, no it’s not!, it has custom views too, and also some styles…, but wait, wait, wait, wait, wait, wait, wait, wait, Android Studio has crashed.</blockquote><p>The compiler is your best friend here, that’s why you are going to hate it soooo much.</p><p>Also supporting your testing setup when migrating to a multi-module one is part of this amazing journey of self discovery. But we don’t want to spoil this epiphanic experience, you’ll have to experience it yourself.</p><h3>3. Con(cl)(f)usion?</h3><p>Modularizing pays off only if your code base doubles its size starting to count from when you thought that modularizing was needed. The proportion is pointless, but the point is clear.</p><p>Keeping components isolated by modules guarantees that the build time -and the cognitive pain- won’t increase endlessly as the app is growing adding new features. Also, Google itself seems to be encouraging multi module setups based on its last announcement: <a href="https://developer.android.com/guide/app-bundle/">App Bundles</a>. And you know, Google is always right, even if it’s wrong.</p><p>To make things (even more) clear, modularizing is something that you want to be done, but not by you.</p><h3>4. What about that StringPatchers thing?</h3><p>Oh yeah funny story. When we moved all xml resources to a common module to be accesible from any other module, their priority when merging resources became the same as the one from any other library. That priority is not publicly documented. Therefore, because an internal detail, the “app_name” string resource from a library named <a href="https://github.com/cookpad/StringsPatcher">StringPatchers</a> was prioritized over Cookpad.</p><p>If you are wondering if this bug hit <a href="https://play.google.com/store/apps/details?id=com.mufumbo.android.recipe.search">production</a>, the answer is clear: the ones who caused it are the same who are writing this, still as part of Cookpad team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3451afed898f" width="1" height="1" alt=""><hr><p><a href="https://sourcediving.com/a-tragic-tale-about-people-having-fun-modularizing-things-that-were-no-longer-an-android-app-3451afed898f">A tragic tale about people having fun modularizing things that were no longer an Android app</a> was originally published in <a href="https://sourcediving.com/">Source Diving</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>