<?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 Erick Sumargo on Medium]]></title>
        <description><![CDATA[Stories by Erick Sumargo on Medium]]></description>
        <link>https://medium.com/@ericksumargo888?source=rss-ac79e61882e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R4eCc8mLFMmA2R3lW-2BQg.jpeg</url>
            <title>Stories by Erick Sumargo on Medium</title>
            <link>https://medium.com/@ericksumargo888?source=rss-ac79e61882e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:48:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ericksumargo888/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[Stop Crafting Your “Time Bomb”]]></title>
            <link>https://proandroiddev.com/stop-crafting-your-time-bomb-39f2d26987e0?source=rss-ac79e61882e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f2d26987e0</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[temporal-coupling]]></category>
            <dc:creator><![CDATA[Erick Sumargo]]></dc:creator>
            <pubDate>Tue, 23 Mar 2021 20:34:41 GMT</pubDate>
            <atom:updated>2022-01-16T03:39:44.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bSUbzRFsH41RZTn0" /><figcaption>Photo by <a href="https://unsplash.com/@cdrying?utm_source=medium&amp;utm_medium=referral">C Drying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A horrible design pattern we should get rid of. Period.</h4><ul><li>Featured in <strong>Kotlin Weekly</strong> - Issue #243:</li></ul><p><a href="https://mailchi.mp/kotlinweekly/kotlin-weekly-243">Kotlin Weekly #243</a></p><ul><li>Featured in <strong>Elegant Objects</strong> site:</li></ul><p><a href="https://www.elegantobjects.org/">Elegant Objects</a></p><p>Fellow devs, do you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea585a80624ffe018f0d41ed6234632a/href">https://medium.com/media/ea585a80624ffe018f0d41ed6234632a/href</a></iframe><p>I’m pretty sure such above classic question has transformed into a situation where every Android dev should have been familiar. And I believe each of you is able to advocate your own why-s for each above option (or do you even really care?). In fact, the Framework team has already sounded as well related this:</p><blockquote>General rule: <br>During any kind of initialization, let the super class do their work first. <br>During any kind of finalization, you do your work first.</blockquote><blockquote>Dianne Hackborn</blockquote><p>Well, regardless of which option you advocate for, or the general rule by Dianne Hackborn, this post doesn’t join in promoting entry which option is the most valid one given with some scenarios, for instance. Which option you should always work with, a best practice. Doesn’t matter.</p><p>In fact, this post is more interested in noticing us to a warning, a sign where we’re actually under a critical situation, a situation forcing us to write a brittle procedural code, a buggy one (we just don’t know it yet), an anti-pattern, the <strong>temporal coupling.</strong></p><h3>Temporal Coupling</h3><p>Or <strong>TC</strong> for brevity. Based on Wikipedia&#39;s <a href="https://en.wikipedia.org/wiki/Sequential_coupling">definition</a>¹:</p><blockquote>Sequential coupling (also known as temporal coupling) is a form of coupling where a class requires its methods to be called in a particular sequence.</blockquote><p>Pretty descriptive, but allow me to generalize and extend the definition a little bit:</p><blockquote>TC is a coupling when some methods are required to be called in a particular order because there is a hidden knowledge about that order and should be recalled correctly.</blockquote><p>Still vague? let’s adhere following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd5f8a2406662618caef271e08d7fb96/href">https://medium.com/media/cd5f8a2406662618caef271e08d7fb96/href</a></iframe><p>We can see line-3 is coupled with the previous line. The snippet most likely implies,</p><p><em>“to calculate the area of the circle, you need to set its radius beforehand. Failing to do so, the program will simply throw an exception.”</em></p><p>See? This is exactly what I refer to as <em>hidden knowledge</em> about the order. Moreover, omitting line-2 will not trigger any lint. You won’t be prompted if you lack something factor to make this program compile. Trying to run it will simply throw an exception. Well, depends on the actual implementation though. The point is you just need to keep this hidden knowledge for yourself, or you write the <a href="https://kotlinlang.org/docs/kotlin-doc.html">KDoc</a>² just in case to save yourself and your successors in the future.</p><p>Let’s admit the bomb side-effect by the above circle example is pretty straightforward to spot on. You simply receive back the explicit thrown exception report and you instantly appear with your fix. Not a big deal. Now let’s add the second example.</p><p>Here we have a few coupled methods, the order is fixed since they share some states mutated somewhere behind those complex multi-layer APIs, and the executions are done in multi-threading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c67dc6b6da351344b7029c893d379fb/href">https://medium.com/media/2c67dc6b6da351344b7029c893d379fb/href</a></iframe><p>Given those constraints, one subtle mistake harming the integrated order may probably cause, well, the program still compiles, integration test shows green passes somehow, but sometimes you find it works improperly, unexpected result, intermittent bugs. You have no option left but to plunge yourself back into a massive tangled mess, day and night spent decoding hidden knowledge of every line you/ predecessor had written, all to trace the root cause.</p><p>You may wonder, isn’t this example kinda a bit dramatic? Not really. This is based on my experience being junior dev supported legacy code on his 2nd sprint. Sounds hellish? You bet. <strong>This second example exhibits the worst BANG effect of TC I’ve witnessed up today.</strong></p><h3>The Dead-End</h3><p>Glad to still have you here because the insight part is about to start. Now let’s head back to the very starting example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea585a80624ffe018f0d41ed6234632a/href">https://medium.com/media/ea585a80624ffe018f0d41ed6234632a/href</a></iframe><p>As I stated earlier, you have a solid statement for whichever option you represent, but turns out a mere hidden knowledge for you. The call super and your TODO magic are inseparable, coupled, a brittle code you’re producing...</p><p>Now, what chances do we have for refactoring? I could say nothing much. What to blame here?</p><h3>open (Kotlin)/ public (Java) is TC’s agent</h3><p>I won’t renounce every single open modifier implementation as smell. open for class? Why not? Subtyping is a virtue in OOP world (though I personally suffice with abstract only all this time). open for API? that’s the issue.</p><p>Every time you are going to open your method, you should take into account that you may risk its entire hierarchy class system. How so? let me clarify:</p><ul><li>Is there a contract design that requires the successor to invoke its super call?</li><li>Is there a contract design that requires the successor should invoke its super call before/ after new implementation?</li></ul><p>As far as I remember, there’s no such privilege in today&#39;s OOP feature (at least by nature). So if the successor disregards the above points, what could go wrong with your entire class system? — Your answer.</p><p><em>“Read my implementation first, then decide your execution order”, </em>this pretty much sums up what your super method could only hope for. That said, it’s the same as you point a gun to your successors to write their TC structure, so to speak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnPz_65XaIFe7GL-RbGobw.png" /><figcaption><a href="https://martinfowler.com/bliki/CallSuper.html">CallSuper by Martin Fowler</a>³</figcaption></figure><p>I’m pretty sure the framework team who designed the Fragment class aware of the aforementioned risk. But they’re part of Google. They are able to create any workaround to unblock themselves from any particular issue and <a href="https://developer.android.com/reference/androidx/annotation/CallSuper">@CallSuper</a>⁴ is apparently their answer. Solution? Shame. If they could limit its visibility to <a href="https://developer.android.com/reference/androidx/annotation/RestrictTo.Scope">internal library scope</a>⁵ only, I could respect whatsoever limitation they are having. <strong>But the fact is they’re misleading, supporting smell practice that should be eliminated by any chance.</strong></p><h3>The Mastermind</h3><p>TC is nothing but a procedural design in essence. But what motivates us to write so?</p><p>Take the above examples, what do circle and onDestroy callback samples share in common? We can see both business part executions actually rely on the outcome of a side effect, as some states of a system changed, mutated, see radius for the circle and mCalled flag abstracted over super.onDestroy() invocation. Not want to limited by those examples, as far I’m experiencing, spotting a TC structure always implies a good sign somewhere amid there exists a wild mutation point, a critical point that we cling to all this time. Without it, we then have no reason at all to bundle our procedural calls with a fixed order to remember. We should worry no more about altering the order because it’s side effect free without affecting consequent calls.</p><p>Now that we should have grasped much enough about what TC is, we arrive at a point where we should be able to sum up who the mastermind behind the <em>“hidden knowledge”</em> term is.</p><h3>Mutable Objects</h3><p>Loads of references suggest preferring immutable over mutable one like stated in <a href="https://leanpub.com/effectivekotlin"><em>Effective Kotlin</em></a><em>⁶</em> (recommended one) by <a href="https://medium.com/u/171dab54cea9">Marcin Moskala</a>. The followings are my top 3 highlights:</p><ol><li><em>It is harder to understand and debug a program with many mutating points. The relationship between these mutations needs to be understood, and it is harder to track how they changed when there are more of them. A class with many mutating points that depend on each other is often really hard to understand and to modify. It is especially problematic in case of unexpected situations or errors.<br> — <br></em>Couldn’t agree more on this. Similar to everything I’ve been preaching about the journey, the mastermind who gives birth to a bad design, TC.</li><li><em>It requires proper synchronization in multithreaded programs. Every mutation is a potential conflict.</em><br> — <br>This can be relatable when you’re the new guy for a big project, you spot a lot of mutation points from the legacy code you support, shared states accessed by multi-thread, and finally new intermittent bug report files in. The inconsistent states one to another debugging session, deadlock, race condition, well well... if I am asked to depict “hell” in the programming world, this is.</li><li><em>When state mutates, often some other classes need to be notified about this change. For instance, when we add a mutable element to a sorted list, once the element is changed, we need to sort this list again.</em><br> — <br>Pretty sure <a href="https://medium.com/u/55d3c15694bb">Sam Edwards</a> could relate this one after his flow emission <a href="https://handstandsam.com/2021/01/15/my-mutablestateflow-didnt-emit/">incident</a>⁷.</li></ol><p>Given the aforementioned drawbacks, it does sound like we try to corner, black sheep-ing object mutation as a smell pattern, error-prone. Well, at least those facts lead us to conclude so. Now, shall we renounce any mutability relevance? Good ambition though, but I’d say still unlikely for today’s enterprise system. We may claim that we totally design our codes with immutability-oriented, but we somehow skip the fact that we literally still depend on framework(s) that rely on mutability idea in essence. Take, for example, class Date from JDK.</p><p>My point is that introducing mutating point(s) isn’t totally a sin. Hard to reason code (buoyed by random mutating points premise), a spaghetti code is. A minimal solution I can suggest is by limiting mutability. My 2 cents: design your architecture, a pattern, drive the readers to predict the way you mutate states, take the MVI architecture/ UDF pattern. This way, the more mutating points we can limit, the more maintainable, easier to reason, more scalable our code is.</p><p>On the other hand, Kotlin grasps the importance of immutability design, becoming one of the modern programming languages that treat immutability on par with its mutable counterpart. As per this tweet, it’s good to see the team still holds firm to the very commitment, promoting immutability adoption to be as easy as mutable one. A future first-class candidate, hopefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zks-FuzAz5VHKoNnMwVZMQ.png" /><figcaption>Tweets by Roman Elizarov</figcaption></figure><h3>Elegant Objects — Intermezzo</h3><p><em>Did I already realize that TC should be a smell pattern? Yes.</em></p><p><em>Did I decide it as my personal anti-pattern ever since? Not really.</em></p><p><em>Even, did I know such a writing structure named temporal coupling? Nope.</em></p><p>Until I stumbled upon an OOP paradigm alternative — <a href="https://www.elegantobjects.org/">Elegant Objects</a>⁸ (EO) by <a href="https://medium.com/u/e3e2f67d9aff">Yegor Bugayenko</a>. Basically, EO renounces some of what we know today’s OOP practices, a new perspective. I find some of its principles fit me, reasonable to work with, <a href="https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html">Objects Should Be Immutable</a>⁹ (again), <a href="https://www.yegor256.com/2015/05/07/ctors-must-be-code-free.html">Constructors Must Be Code-Free</a>¹⁰, its trump card <a href="https://www.yegor256.com/2015/02/26/composable-decorators.html">Composable Decorators</a>¹¹, just to name a few. I just like the way he conveys his objection, some by empirical proven, bold rather than a vague statement, a high recommendation.</p><blockquote>Caveat:<br>After EO, you probably find yourself a bit slower when designing codes at the start. Now you have a new set of standards, you’re no longer what you used to, you’re a better critical thinker now. You have a number of options to be considered before into any decision, all to extract a better design with maintainability and extensibility as your main focus.</blockquote><h3>Closing</h3><p>The takeaway from this post is simple. Don’t write temporal coupling code <strong>by any chance</strong>. Now refer to your codebase, try to spot one. If any, take a lean step and start to refactor it. Don’t even leave it as a temporary tech-debt. TC issue is real, I’ve witnessed the various great damage it could lead to, yet, major developers tend not to see it coming (as far I run myself as a reviewer). Notice the design patterns you’re using, especially the one that mutates objects as it’s a symptom that might lead to producing a brittly TC code.</p><p>With the aforementioned credits, external references, give them a shot. Start with a peek, try to reason every statement they concern about, scenario examples, you’ll learn something new there. They’ll shape how you think, make decisions, and contribute to a better design code you will write.</p><p>You can also find me at <a href="https://github.com/ErickSumargo">Github</a> and <a href="https://twitter.com/SumargoErick">Twitter</a>.</p><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/Sequential_coupling">https://en.wikipedia.org/wiki/Sequential_coupling</a></li><li><a href="https://kotlinlang.org/docs/kotlin-doc.html">https://kotlinlang.org/docs/kotlin-doc.html</a></li><li><a href="https://martinfowler.com/bliki/CallSuper.html">https://martinfowler.com/bliki/CallSuper.html</a></li><li><a href="https://developer.android.com/reference/androidx/annotation/CallSuper">https://developer.android.com/reference/androidx/annotation/CallSuper</a></li><li><a href="https://developer.android.com/reference/androidx/annotation/RestrictTo.Scope">https://developer.android.com/reference/androidx/annotation/RestrictTo.Scope</a></li><li><a href="https://leanpub.com/effectivekotlin">https://leanpub.com/effectivekotlin</a></li><li><a href="https://handstandsam.com/2021/01/15/my-mutablestateflow-didnt-emit/">https://handstandsam.com/2021/01/15/my-mutablestateflow-didnt-emit/</a></li><li><a href="https://www.elegantobjects.org/">https://www.elegantobjects.org/</a></li><li><a href="https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html">https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html</a></li><li><a href="https://www.yegor256.com/2015/05/07/ctors-must-be-code-free.html">https://www.yegor256.com/2015/05/07/ctors-must-be-code-free.html</a></li><li><a href="https://www.yegor256.com/2015/02/26/composable-decorators.html">https://www.yegor256.com/2015/02/26/composable-decorators.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f2d26987e0" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/stop-crafting-your-time-bomb-39f2d26987e0">Stop Crafting Your “Time Bomb”</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[Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 2)]]></title>
            <link>https://proandroiddev.com/personal-request-changes-materials-starter-pack-kotlin-ver-part-2-426084b9c9a1?source=rss-ac79e61882e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/426084b9c9a1</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Erick Sumargo]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 08:36:11 GMT</pubDate>
            <atom:updated>2020-11-01T11:21:50.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wgv1b2AhAq02emzS" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Continuing the 1st part:</p><p><a href="https://proandroiddev.com/personal-request-changes-materials-starter-pack-kotlin-ver-part-1-9a938f3768ad">Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 1)</a></p><h3>7. Public Methods as API Contracts</h3><h4>Background:</h4><p>Direct concrete object interaction with its encapsulated public methods is considered a bad design. <a href="https://www.yegor256.com/2014/11/20/seven-virtues-of-good-object.html">A good object should always work by contracts</a>¹²; this simple mantra. But if one is still highly skeptical with this non-trivial mantra, at least they need to understand that it’s under-backed by 2 big names, <strong>EO</strong> and <strong>SOLID.</strong></p><p>There are at least 2 practical reasons why you want to satisfy <strong><em>ME,</em></strong> the <strong>M</strong>aintainability &amp; <strong>E</strong>xtensibility factors. Given a design:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729225b804f0c1581c4d818e002b82ee/href">https://medium.com/media/729225b804f0c1581c4d818e002b82ee/href</a></iframe><p>Regarding the above naive design, assume:</p><ul><li><strong>(M)</strong> There are hundreds of TextRandom declarations scattered over A to Z modules. Somehow the TextRandom is decided to be renamed (like for real!?). If this is the Android platform that we’re under developing, is it worthed for the recompiling penalty by those impacted modules because of such a trivial change?</li></ul><blockquote>Bonus: Be prepared as well to request each module owner approval. 😭</blockquote><ul><li><strong>(M)</strong> While in UT, how would one be able to represent the fake version of the TextRandom object? Well, correct me but it’s impossible except relying on “magics” from some capable mock libraries which could probably turn to <a href="https://breadcrumbscollector.tech/beware-of-chicken-testing-or-mocks-overuse/">unreliable</a>¹³ and <a href="https://www.yegor256.com/2014/09/23/built-in-fake-objects.html">unmaintainable</a>¹⁴ testing.</li></ul><blockquote>Bonus: Like the old saying, there will always be a price for a hidden “magic”. So try to adapt if each test should take a little bit longer to complete. 😭</blockquote><ul><li><strong>(E)</strong> Among A to Z modules, <strong>X</strong> has a new requirement that any special character should be removed from the generated text and it should be capitalized as well. So how would one add these functionalities by preserving the old generate implementation so the other modules can still have the original behavior benefit?</li></ul><h4>Mitigation:</h4><p>The idea is simple. Create a contract with those public signature methods as part of the APIs and have the Concreter implements its counterpart based on the contract which results in a high decoupling code.</p><p>Thanks to this abstraction, this benefits us by protecting the high-level modules (Client) from any further implementation change by the lower one (Dependency). Besides, we too can create the fake version of the dependency naturally without any “magic” aid in UT’s context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/016aaf7f37c5f2f3847b3e9fb4850b1e/href">https://medium.com/media/016aaf7f37c5f2f3847b3e9fb4850b1e/href</a></iframe><p>Meanwhile, here is the suggested design for the text decorating requirement will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bcaf82f63a169d1e1b5c3a52cbf8287/href">https://medium.com/media/7bcaf82f63a169d1e1b5c3a52cbf8287/href</a></iframe><p>Thanks for the equipped contract interface, now we can apply the “<a href="https://chercher.tech/kotlin/decorator-design-pattern-kotlin">decorator pattern</a>¹⁵” for the new TextWithNoSpecialCharacter and TextWithCapitalized features.</p><p>Check out how we construct the requirement in a <strong>composed</strong> and <strong>declarative</strong> fashion. By this great extensible foundation, now we welcome every new text decorator feature with zero extensibility worries in the future. Remember, the more (useful) abstraction we add, the more flexibility we earn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*IgoS7_FUhn6FEh0SQ1SfVg.gif" /><figcaption>Captain America in Endgame</figcaption></figure><blockquote>Note:</blockquote><blockquote>1. The decorator is my favorite among all other patterns I’m aware of. It is a very simple but very powerful mechanism to respect the S<a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle"><strong>O</strong></a>¹⁶LID<strong> </strong>in very well manner.</blockquote><blockquote>2. Some might argue with the decorator pattern vs extension method topic. Please note that <strong>it’s not about adding new methods. It’s about adding new functionality to existing methods.</strong></blockquote><blockquote>Decorator is actually defined as using wrapping classes concept which will allow us to alter behaviour dynamically at runtime -- something we couldn’t do with the compiled static extension method.</blockquote><h3>8. The “Immigrant” Singleton</h3><p>a.k.a. Singleton inside a method. No doubt but my bread and butter view in some major code review activities. Consider a design:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78c6539297a99d3b67e4cbbfd25da5c4/href">https://medium.com/media/78c6539297a99d3b67e4cbbfd25da5c4/href</a></iframe><p><strong>*Typical me every time reading after:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*EtbHFUvlyB1Mhls8tj8CQw.png" /><figcaption>Gordon Ramsay in HK</figcaption></figure><h4>Background:</h4><p>The problem is not with the Singleton <em>per se</em>. It usually shines under circumstances, memory usage for instance.</p><p>There we can see the Presenter is tightly coupled with the Singleton which means the code is <a href="http://www.adapttransformation.com/devops-journey/transformation/tightly-coupled-code/">dead-end, error-prone</a>¹⁷, and with the all bad <strong>WHYs</strong> issued at the previous factor.</p><h4>Mitigation:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e1d6b41a8d059895789bd8673ec9a1/href">https://medium.com/media/d7e1d6b41a8d059895789bd8673ec9a1/href</a></iframe><p>With hidden DateUtils details over a contract and strategic injectable position, this comes with at least 2 benefits:</p><ul><li>The loosely-coupled design which resulting reusable Presenter codes with flexible/switchable behavior of dateManager dependency in the latter,</li><li>Faking out the dateManager dependency is much easier on the testing side.</li></ul><h3>9. Constructors Should Be Code-Free</h3><p>Are you coding in imperative or declarative style? If an imperative adopter, then this factor might oppose the belief, or if you think it’s going to be hard to follow this factor part, you may skip. Else, now we are going to learn how a constructor injected with some side-effects is a bad practice.</p><h4>Background:</h4><p>In declarative programming, we try to delay for as long as possible any calculation which introduces to a side-effect, until it is requested by the object owner (client). Now, here comes a constructor with 99% responsibility is done within:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25043f5dde54bf5be827aec505b1766d/href">https://medium.com/media/25043f5dde54bf5be827aec505b1766d/href</a></iframe><p>Alright, now I’ll try my best to dictate what possible reason lies over the design (assume the file is read-only):</p><blockquote>“Why should I re-read the content from a given fileName when I can have it done once enough? The readContent will then need to return same content result every time it is requested which will resolve time performance issue. Constructor init block should be a perfect site for that.”</blockquote><p>Now the side-effects afterward:</p><ul><li>The class is dead-end, preventing against from any advanced behavior extension/composition of its object,</li><li>One didn’t consider if somewhere APIs will try to delete the corresponding file. The above design will keep returning consistent content although the file has just been deleted.</li></ul><h4>Mitigation:</h4><p>We know why methods exist for. Try to atomize and delegate the behaviors/responsibilities to them. We don’t want to get charged extra penalty time for every object instantiation because its constructor contains some relatively complex logic which is supposed only to create an instance from it or some local value mapping assignments.</p><p>If we have the same concern time performance as thought above, we could create another composition FileReaderCached version to store the operating result by leveraging some APIs facilitated by each programming language (Cacheable annotation in Java/by lazy delegation in Kotlin). A sum up,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*1eLSB9OzTCNch0SUHnEFQw.png" /><figcaption>“Always has been” meme</figcaption></figure><h3>10. A Class is Either Final or Abstract</h3><p>A bold statement from <a href="https://www.yegor256.com/2014/11/20/seven-virtues-of-good-object.html"><em>“Seven Virtues of a Good Object¹²”</em></a> where I really felt into EO’s gang at that time.</p><p>The main idea of this statement is there shouldn’t exist any inheritance material, like open modifier in Kotlin because inheritance is <em>“</em><a href="https://www.infoworld.com/article/2073649/why-extends-is-evil.html"><em>evil</em></a><em>¹⁸”</em>. Why? Consider a black box (final) class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a25d5598f778d767f142bc1a8c30e437/href">https://medium.com/media/a25d5598f778d767f142bc1a8c30e437/href</a></iframe><p>The black box looks fine. But assume a new requirement in which the generated random text should contain number only (not limited to). So one naively proposes the original generate behavior can just be extended with some necessary logic. Hence, they extend the entire black box class to satisfy the come-up plan:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83db9fd074eb923ab6c799eca2d850ff/href">https://medium.com/media/83db9fd074eb923ab6c799eca2d850ff/href</a></iframe><p>Now the requirement is completed but the maintainability is at risk. We have no idea what could go wrong afterward. Please note that once we override the generate method with a new piece of implementation in the child class, we risk breaking the logic of the entire parent class since all the internal methods start using this new generate version.</p><blockquote>FAQ:</blockquote><blockquote>So how about the abstract class? Isn’t it leveraging the concept of inheritance too?</blockquote><p>Correct, but only into the places the class allows us to touch, in which explicitly marked abstract methods. The class is “broken” and ready for any derivation. Some of its methods are not functioning which is expecting us to inject some implementation by overriding them. Nothing more than, the class defends its fixed behaviors (no marked open in Kotlin) from getting any advanced extension.</p><h4>Mitigation:</h4><p>Any come-up class extension idea should be done <strong>isolated</strong>, zeroing any harmful potential behavior break of an entire concrete parent class. Thus, always prefer the <em>“</em><a href="https://en.wikipedia.org/wiki/Composition_over_inheritance"><em>Composition over inheritance</em></a><em>¹⁹”</em> mantra with “<a href="https://chercher.tech/kotlin/decorator-design-pattern-kotlin">decorator pattern</a>¹⁵” as one of our tools.</p><blockquote>Fact: Even worse scenario, one inherits an entire class because they just want to reuse some boilerplates. At that time, he/she has just about:</blockquote><blockquote>- Turning their working-class into what is called the “God Class”,</blockquote><blockquote>- Going to offend the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle"><strong>S</strong></a>⁷O<a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle"><strong>L</strong></a>²⁰ID at some point,</blockquote><blockquote>- Breaking encapsulation -- knowing what it isn’t supposed to.</blockquote><h3>11. The Temporal Coupling</h3><p>As the saying goes, “Save the best for last”.</p><p>IMO this last factor is a symptom, a time bomb, hides the most horrible design smell potential, more horrible than the classic NPE, yet, some developers today tend to don’t see that coming (at least based on my observation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*VyyRvMvPzLT0WScBS_LA0Q.gif" /><figcaption>Gus Fring in Breaking Bad</figcaption></figure><h4>Background:</h4><p>Usually found in imperative programming style, temporal coupling happens when some sequential methods call must stay in a particular order (coupled), but the knowledge about that order is hidden and must be remembered precisely by the one who codes.</p><p>The order is also easy to break, typically when in refactoring, and the compiler won’t catch it for us. Hence, that usually produces day and night efforts spent on fixing some found “strange” bugs.</p><p>The following snippet to visualize the temporal coupling issue in the simplest form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9dd24cd32c4e102f97f4fefe22142ab/href">https://medium.com/media/f9dd24cd32c4e102f97f4fefe22142ab/href</a></iframe><p>We can see at line 4 is temporal coupled with line 3. Try removing line 3 will not trigger any error compilation and calculating the area before the required radius is settled will throw an exception (or return a default result, depend on implementation). This is what we called the “hidden knowledge”.</p><h4>Mitigation:</h4><p>Numerous design patterns could solve this issue, constructor injection as one of. With the params injection at the moment of object creation, we ensure the radius is always visible before any further dependent operation is requested. This shall eliminate the need to call two methods in sequence.</p><p>IMO, still, that kind of solution is nothing more than a temporal workaround. We should come forward instead with effective mitigation to prevent similar issues continue occurring in our codebase. A big picture of mine would be if only in this object-oriented world is fitted with more good objects; immutable objects, or practically by not introducing any API (setter) which could mutate an object’s internal state after it created, I believe this temporal coupling issue shouldn’t be about to exist.</p><blockquote>Note:</blockquote><blockquote>The immutable object is one of the very important factors I wish to bring in this 2nd part. But due to it’s never been short, I think it deserves to have its own part.<br><br>But if you’re eager to find how it became a thing, please refer to this <a href="https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html">great article</a>²¹ and <a href="https://www.yegor256.com/2014/12/09/immutable-object-state-and-behavior.html">this</a>²² as well for why we should prefer immutability over mutability now. That reading probably will also change our bias on how we see and treat an object before.</blockquote><h3>UPDATE</h3><p>I implement custom lints based on the above factors. Check it out:</p><p><a href="https://github.com/ErickSumargo/Cross">ErickSumargo/Cross</a></p><h3>Closing</h3><p>That’s it. That’s all about my compilation code review factors, for now. <strong>Part 3</strong> is on the road-map, and those who seek my approval signal, better validate if the changes violate one of these factors.</p><p>And of course, these factors are just bundles of arguments. An argument welcomes any constructive criticism. So if you have one, feel free to state on comment below :)</p><p>External links:</p><ol><li><a href="https://en.wikipedia.org/wiki/Sentinel_value#:~:text=In%20computer%20programming,%20a%20sentinel,a%20loop%20or%20recursive%20algorithm">https://en.wikipedia.org/wiki/Sentinel_value#:~:text=In%20computer%20programming,%20a%20sentinel,a%20loop%20or%20recursive%20algorithm</a>.</li><li><a href="https://leanpub.com/effectivekotlin">https://leanpub.com/effectivekotlin</a></li><li><a href="https://en.wikipedia.org/wiki/Fail-fast">https://en.wikipedia.org/wiki/Fail-fast</a></li><li><a href="https://tenor.com/view/javascript-hadouken-code-programming-gif-16271428">https://tenor.com/view/javascript-hadouken-code-programming-gif-16271428</a></li><li><a href="https://testing.googleblog.com/2017/06/code-health-reduce-nesting-reduce.html">https://testing.googleblog.com/2017/06/code-health-reduce-nesting-reduce.html</a></li><li><a href="https://en.wikipedia.org/wiki/God_object">https://en.wikipedia.org/wiki/God_object</a></li><li><a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">https://en.wikipedia.org/wiki/Single-responsibility_principle</a></li><li><a href="https://en.wikipedia.org/wiki/Guard_(computer_science)">https://en.wikipedia.org/wiki/Guard_(computer_science)</a></li><li><a href="https://www.elegantobjects.org/">https://www.elegantobjects.org/</a></li><li><a href="https://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html">https://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html</a></li><li><a href="https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself">https://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself</a></li><li><a href="https://www.yegor256.com/2014/11/20/seven-virtues-of-good-object.html">https://www.yegor256.com/2014/11/20/seven-virtues-of-good-object.html</a></li><li><a href="https://breadcrumbscollector.tech/beware-of-chicken-testing-or-mocks-overuse/">https://breadcrumbscollector.tech/beware-of-chicken-testing-or-mocks-overuse/</a></li><li><a href="https://www.yegor256.com/2014/09/23/built-in-fake-objects.html">https://www.yegor256.com/2014/09/23/built-in-fake-objects.html</a></li><li><a href="https://chercher.tech/kotlin/decorator-design-pattern-kotlin">https://chercher.tech/kotlin/decorator-design-pattern-kotlin</a></li><li><a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle</a></li><li><a href="http://www.adapttransformation.com/devops-journey/transformation/tightly-coupled-code/">http://www.adapttransformation.com/devops-journey/transformation/tightly-coupled-code/</a></li><li><a href="https://www.infoworld.com/article/2073649/why-extends-is-evil.html">https://www.infoworld.com/article/2073649/why-extends-is-evil.html</a></li><li><a href="https://en.wikipedia.org/wiki/Composition_over_inheritance">https://en.wikipedia.org/wiki/Composition_over_inheritance</a></li><li><a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle">https://en.wikipedia.org/wiki/Liskov_substitution_principle</a></li><li><a href="https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html">https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html</a></li><li><a href="https://www.yegor256.com/2014/12/09/immutable-object-state-and-behavior.html">https://www.yegor256.com/2014/12/09/immutable-object-state-and-behavior.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=426084b9c9a1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/personal-request-changes-materials-starter-pack-kotlin-ver-part-2-426084b9c9a1">Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 2)</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[Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 1)]]></title>
            <link>https://proandroiddev.com/personal-request-changes-materials-starter-pack-kotlin-ver-part-1-9a938f3768ad?source=rss-ac79e61882e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a938f3768ad</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Erick Sumargo]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 08:35:14 GMT</pubDate>
            <atom:updated>2020-11-01T11:19:17.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dC9Ij1F4IPvstRgE" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ul><li>Featured in <strong>Android Weekly</strong> - Issue #432:</li></ul><p><a href="https://androidweekly.net/issues/issue-432">Android Weekly - Free weekly Android &amp; Kotlin development newsletter</a></p><ul><li>Featured in <strong>Kotlin Weekly</strong> - Issue #217:</li></ul><p><a href="https://mailchi.mp/kotlinweekly/kotlin-weekly-217">Kotlin Weekly #217</a></p><p>It’s nice to have personal documented guides, it’s such time-saving instead of rewriting similar arguments in every code review activity. Without further ado, below are my <em>coarse-grained</em> compilation factors taken into every review action <strong>(reading in order is recommended)</strong>:</p><h3>1. No Meaningless Nullable Primitives</h3><h4>Background:</h4><p>Performance is critical optimization, memory for an instance. Object creation can sometimes be expensive and always cost something. On the other hand, Kotlin supports a variable is either non-null or nullable for any data type, including primitives.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68e46c17eef82a9a6821a4c44aeddc10/href">https://medium.com/media/68e46c17eef82a9a6821a4c44aeddc10/href</a></iframe><p>For the sake of having the default null as the starting value, I don’t think that gives enough reason why one prefers nullable primitive to a non-null version but with default <a href="https://en.wikipedia.org/wiki/Sentinel_value#:~:text=In%20computer%20programming%2C%20a%20sentinel,a%20loop%20or%20recursive%20algorithm.">sentinel value</a>¹ as a starting state.</p><blockquote>FAQ:</blockquote><blockquote>The question now is why am I so strict with this nullable primitive stuff?</blockquote><p>Below is java decompiled comparison between the one with a nullable primitive and the other with a non-null version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b52cb42f1c5bfafacea9dc6ae6762325/href">https://medium.com/media/b52cb42f1c5bfafacea9dc6ae6762325/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a5a04ba8290bfaa16a8dd127510a9ad/href">https://medium.com/media/8a5a04ba8290bfaa16a8dd127510a9ad/href</a></iframe><p>Nothing differs, except: Integer vs int. Under the hood, the nullable Int is compiled into using Integer type instead of primitive int because primitive cannot hold null value and cannot be used as a type argument.</p><p>Integer is a class along with its companion methods, thus you create an object from it which introduces an unnecessary overhead to the memory. Citing some statements from the <a href="https://leanpub.com/effectivekotlin"><em>Effective Kotlin</em></a><em>²</em> book (you should have one) to give us a picture of some cost in object creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-CqupA5T0jv0IChlk5znw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zs1_PLrNymPegav8M86k6g.png" /><figcaption>Effective Kotlin- Item 45: Avoid unnecessary object creation</figcaption></figure><h4>Mitigation:</h4><p>Instead of introducing extra overheads to memory, if we literally don’t have any strong reason for marking a primitive as nullable, then don’t. We should be fine enough with the below one instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/675159ee82720bf25dba128cb064cae8/href">https://medium.com/media/675159ee82720bf25dba128cb064cae8/href</a></iframe><h3>2. Kotlin’s Named Arguments</h3><p>Consider a scenario:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8a08ef5041cc42cc6555516512eb801/href">https://medium.com/media/c8a08ef5041cc42cc6555516512eb801/href</a></iframe><h4>Background (*literally me after reading):</h4><p><em>“Is it the ordinal sum of 1 and 5, or summing from 1 to 5, or other else? This is way too ambiguous.”</em></p><h4><strong>Mitigation:</strong></h4><p>I tolerate if those arguments are abstracted with variable names that match the declared parameter names. Else, try to explicitly set which parameter you try assigning to. This helps future readers obtain instant comprehension without spending their time jumping to the declared blueprint. They will thank you as well as yourself, probably.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bea8fab71dd65a292de84fc3fea9344/href">https://medium.com/media/6bea8fab71dd65a292de84fc3fea9344/href</a></iframe><h3>3. The Expressivity of Kotlin’s Elvis Operator</h3><p>Consider an implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d257faeeda11309f6f18df8b4468427/href">https://medium.com/media/6d257faeeda11309f6f18df8b4468427/href</a></iframe><h4>Credit:</h4><p>I love the <a href="https://en.wikipedia.org/wiki/Fail-fast"><em>fail-fast</em></a><em>³</em> idea, instead of introducing more complex nested condition checks at the next lines.</p><h4><strong>*A better idea:</strong></h4><p><em>“Actually I’m fine with that code style, though, there’s a better way to unwrap a nullable variable.”</em></p><h4>Mitigation:</h4><p>Elvis operator is more expressive than we thought. The smart cast to non-null invalidation can be done by only expressing the unary operation in the first place. So the suggested below will do the same work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2abec8288f9077ab11c29c2bbd9c2f91/href">https://medium.com/media/2abec8288f9077ab11c29c2bbd9c2f91/href</a></iframe><h3>4. Max. 1 Nested Condition Block Tolerance</h3><p>Just my personal number, don’t be too committed 😆.</p><h4>Background:</h4><p>It’s just me seeing too often code structures with deeply nested control flow which could actually be flattened by delegating some flows to other units/methods.</p><p><a href="https://tenor.com/view/javascript-hadouken-code-programming-gif-16271428"><em>Hadoken</em></a>⁴ nested blocks are <a href="https://testing.googleblog.com/2017/06/code-health-reduce-nesting-reduce.html">smell, error-prone to maintain, and hurt readability</a>⁵. They make it just about impossible to tell what code will run, or when. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e7704e6a6d69865580ea07dd1218ab/href">https://medium.com/media/02e7704e6a6d69865580ea07dd1218ab/href</a></iframe><p>In just a sec, tell me under what circumstances code at line 16 will actually run? That’s just about impossible to tell, I guess? That’s the problem.</p><p>Also, typical nested conditions are very often seeing as a “<a href="https://en.wikipedia.org/wiki/God_object">God object</a>⁶”. Knowing too many things on <em>“when to do”</em>, with all its conditions, and it might very likely know many things on <em>“how to do”</em> as well. Yes, what I’m trying to tell here is its potential for violating <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle"><strong><em>S</em></strong></a><em>⁷</em>OLID in the unit scope.</p><h4>Mitigation:</h4><p>Employ <a href="https://en.wikipedia.org/wiki/Guard_(computer_science)">guard clauses</a>⁸ pattern, try to refactor the nested logic into separate methods to achieve a better-flattened structure which leads to faster discoverable bugs, development iteration, and increased stability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bfff38a20a8388987bfa57817e91c7a/href">https://medium.com/media/6bfff38a20a8388987bfa57817e91c7a/href</a></iframe><h3>5. Destructuring Declarations? Not even once</h3><h4>Background:</h4><p>Correct me, but I don’t think there’s such a critical need of how this data class feature exists, even as a compliment <em>per se</em>. It instead introduces potential code breaks since the data class has always been a non-trivial custom wrapper. Consider a snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff12fcfe3929e4b3f17b49a1e3245a61/href">https://medium.com/media/ff12fcfe3929e4b3f17b49a1e3245a61/href</a></iframe><p>Now, someone unintentionally adds a new property mainActor after title:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ad81661ebed32e61d55c1092d008a20/href">https://medium.com/media/7ad81661ebed32e61d55c1092d008a20/href</a></iframe><p>Unfortunately that someone has forgotten to do re-positioning of every existed destructuring. The above code will still compile, but the log result breaks.</p><h4><strong>Mitigation:</strong></h4><p>Forget that feature has ever existed. Consider accessing the props via data class instance instead. Or, you may have tuples (Pair, Triple, …) with their fixed componentN if you couldn’t really escape from the destructuring fashion.</p><h3>6. It’s XUtils</h3><h4>Background:</h4><p>I’m a big fan of the <a href="https://www.elegantobjects.org/"><strong>EO</strong></a>⁹ paradigm but not with the <strong><em>“</em></strong><a href="https://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html"><strong><em>let’s killing Utility classes</em></strong></a><em>¹⁰</em><strong><em>”</em></strong> idea (not a big fan then, I guess 😂). IMHO that should depend on a situation context.</p><p>Sometimes having a utility class is just an inevitable <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>¹¹ favor and that’s fine. But some misfortunes usually turned someone becoming greedy, load in with as many common APIs as they can, until losing respect for the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle"><strong><em>S</em></strong></a><em>⁷</em>OLID. Now, the utility represents irrelevant various responsibilities.</p><h4><strong>Mitigation:</strong></h4><p>Most of the time naming a class can be tricky. The name could drive our intention to define what the class is and how it should be treated. So instead of having such a broad name Utils, I would recommend prefixing the name with some representative of real-world objects, e.g., FileUtils, CalendarUtils, and friends. The signed names could keep our manner on track on how to manage the behavior of a utility class in the latter.</p><p>Continued to the 2nd part…</p><p><a href="https://proandroiddev.com/personal-request-changes-materials-starter-pack-kotlin-ver-part-2-426084b9c9a1">Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 2)</a></p><h3><strong>UPDATE</strong></h3><p>I implement custom lints based on the above factors. Check it out:</p><p><a href="https://github.com/ErickSumargo/Cross">ErickSumargo/Cross</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a938f3768ad" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/personal-request-changes-materials-starter-pack-kotlin-ver-part-1-9a938f3768ad">Personal “Request changes” Materials Starter Pack (Kotlin ver.) (Part 1)</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[Modern Android Security Development]]></title>
            <link>https://proandroiddev.com/modern-android-security-development-f84796824cea?source=rss-ac79e61882e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f84796824cea</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[jetpack-security]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Erick Sumargo]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 17:17:58 GMT</pubDate>
            <atom:updated>2020-09-13T14:02:29.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDCeyYxNhl-VTM0-MtmC-Q.png" /></figure><h4>An Opinionated Ultimate Security Toolbox with Insights</h4><ul><li>Featured in <strong>Kotlin Weekly</strong> - Issue #215:</li></ul><p><a href="https://mailchi.mp/kotlinweekly/kotlin-weekly-215">Kotlin Weekly #215</a></p><ul><li>Featured in <strong>Android Newsletter</strong> - Issue #11:</li></ul><p><a href="https://vladsonkin.com/android-newsletter-11/">Android Newsletter #11</a></p><ul><li>Featured in <strong>onCreate Digest</strong> - Issue #21:</li></ul><p><a href="http://www.oncreatedigest.com/issues/oncreate-digest-issue-21-275465">onCreate Digest - Issue #21</a></p><h4>1st (Mistake) Practice</h4><p>Given the <em>“find out how to en-decrypt data in Android”</em> requirement, what would you do?</p><p>Unless you are a security expert or developer with a security career dedication that writing the cryptographic code from scratch is just a trivial task, it’s very common for us to start “Googling”, deep dive in “Stack Overflow” to find security-related implementation answers until we probably find below similar snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae8f0df0f434e89cedf7291c53533b25/href">https://medium.com/media/ae8f0df0f434e89cedf7291c53533b25/href</a></iframe><h4>Problem:</h4><p>So what‘s wrong with the snippet? The encrypt and decrypt APIs look solid and have our work done, don’t they?</p><p>Well, there’s absolutely nothing wrong with that argument. The interchangeability between the plain and the cipher is proven goes smoothly. But the such old, common, and unsafe to use of the snippet is the most concerning issue we’re really facing now. That issue factors could be the reason that our <em>thought-have-secured</em> assets might be available or easily accessible to an attacker.</p><h4><strong>2nd (Mistake) Practice</strong></h4><p>Let’s have a short scenario:</p><blockquote>Backend engineer: “Keep this JWT token, will you? We need it for some later authorizations.”</blockquote><blockquote>Probably us: “No problem (better say hi to SharedPreferences now).”</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/290179f25413003f0ce47f0154c426a1/href">https://medium.com/media/290179f25413003f0ce47f0154c426a1/href</a></iframe><h4>Problem:</h4><p>By having a rooted phone/device, please note that everyone literally could access our app XML preference file, located inside the internal storage. Talking about JWT token, the token is literally composed of <strong>algorithm-token header type,</strong> <strong>payload,</strong> and <strong>verify signature</strong> parts, each concatenated by <strong>. </strong>. And based on this recommended writing,</p><p><a href="https://medium.com/swlh/hacking-json-web-tokens-jwts-9122efe91e4a">Hacking JSON Web Tokens (JWTs)</a></p><p>You might want to read off what are some potential vulnerabilities, how the attackers can forge, manipulate the token parts, and log in as someone else. The only moral story here we can learn to help to prevent such an issue is to not store the token in raw.</p><blockquote>FAQ:</blockquote><blockquote>“But wait a minute… how are we supposed to act now? We understand if we could encrypt the token before storing it in the preference file or somewhere else should satisfy the issue prevention. But the API we use for the encryption scheme is issued on its own as well at the <strong>1st problem</strong>.”</blockquote><p>Well, if we could have our own set of security arsenal that we can rely on, I personally can state, just go ahead. However, if we have less knowledge of any robust cryptographic algorithm or looking for an official and standardized solution, we may want to refer to the next section.</p><h3>Jetpack Security</h3><p>Or <strong>“JetSec”</strong> for short, introduced at last Android Dev Summit 2019 provides us a high-level abstraction to allow encrypting data, file, until shared preferences easily without having to really understand the ins and outs of security.</p><p>JetSec features <a href="https://developer.android.com/training/articles/keystore"><strong>Android KeyStore</strong></a>¹ which is the mastermind of every cryptographic operation and we may assume all data secured is done via it. Of course, every secured data associates with a private key which is a primary material used for any cryptographic op. In JetSec, these private keys called <strong>keyset</strong>. Android KeyStore stores these keyset materials in a container hardware-backed which makes accessing them very hard and it’s not exportable.</p><blockquote>Note: JetSec also employs <strong>Tink</strong>, a cross-platform, open-source library from Google to leverage the <strong>MasterKey</strong> concept for securing all keysets.</blockquote><p><strong>Gradle Import</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c28711c910c2646f8a7a4600c73c9c/href">https://medium.com/media/91c28711c910c2646f8a7a4600c73c9c/href</a></iframe><p>Now let’s jump into practical data encryption with JetSec.</p><blockquote>Note: The library requires API 23/Marshmallow at minimum.</blockquote><blockquote>I personally wouldn’t mind raising the minSdkVersion bar as a trade-off since some of my projects hold some critical sensitive information.</blockquote><p><strong>MasterKey<br></strong>Before leveraging any toolbox from JetSec, the generation of the MasterKey is a prerequisite. Since the minSdkVersion has been set to 23, we’re allowed to use the default AES-based spec for the key generation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae7a21d7496c5c8692d55ed4dd1fed95/href">https://medium.com/media/ae7a21d7496c5c8692d55ed4dd1fed95/href</a></iframe><p>Though it’s fine for most use cases, we’re also allowed to customize our own spec to secure some of the sensitive data clusters in advance, in case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccc215f1a2e3ea6d1c3f0541f14e22d3/href">https://medium.com/media/ccc215f1a2e3ea6d1c3f0541f14e22d3/href</a></iframe><p><strong>EncryptedFile &amp; EncryptedSharedPreferences<br></strong>I wouldn’t write too far all about these tools, while we can find their functionalities and implementation details <a href="https://developer.android.com/topic/security/data">here</a>². Here are some results of the encrypted content along the generated keyset stored inside files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yczNFUt15Doqa-bFmBqzEQ.png" /><figcaption>EncryptedFile - “Hello World” in ciphertext</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-wfqRohYiGs83lgy5E4sg.png" /><figcaption>EncryptedFile - Generated keyset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FS-zt6BQxyG7Y2oD6ticIw.png" /><figcaption>EncryptedSharedPreferences - JWT “user_token” in ciphertext</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlY-A8ttjS6x-6rqmMeHpA.png" /><figcaption>EncryptedSharedPreferences - Generated keysets</figcaption></figure><blockquote>Note: It’s quite interesting when we find that we literally don’t need to provide our own custom private key string either in a master key generation or when taking both EncryptedFile and EncryptedSharedPreferences in some actions. Hence, we won’t be concerned with another issue about how to secure the private key per se, declared inside the source code. Thanks to the Android KeyStore.</blockquote><p>In addition to JetSec, below are other security tools compliment which I equally highly recommend to strengthen the security factors:</p><h3>SealedObject</h3><p>At some point, we may want to have our serialized objects resided in some <a href="https://www.infoworld.com/article/2076237/signed-and-sealed-objects-deliver-secure-serialized-content.html">untrusted mediums</a>³. JavaX’s SealedObject encapsulates the original object, in serialized format, and encrypts the content to protect its confidentiality.</p><p>SealedObject will cover us in order to prevent someone from tampering with our serialized object, but the reconstituted object may be lacking transient fields or other information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b5a5e58cf819b4b2d9beada28e345f/href">https://medium.com/media/84b5a5e58cf819b4b2d9beada28e345f/href</a></iframe><p>Let’s break-down:</p><ul><li>The sealObject API is for encapsulating the original object as the SealedObject contract states. We then finally store the encapsulated Serializable result in a somewhere medium.</li><li>We decide to retrieve back the serialized object. To verify if the serialization is modified, we testify it via unsealObject API. The API should unwrap back to the original one if the object is proven the same still (of course with the corresponding secret key), else an exception will be thrown.</li></ul><blockquote>Note: We may consider SignedObject and GuardedObject as part of the compliments.</blockquote><h3>R8</h3><blockquote>“One Shot Two Kills”</blockquote><p>It isn’t only reducing the APK/AAB size significantly, R8 contributes to a matter of security context as well. Today, cracking the source code along with embedded resources/assets can be done easily with some simple tools, like the dex2jar converter, Java Decompiler (JD) &amp; friends, even the Android Studio (3.6+) facilitates the APK/AAB analyzer.</p><p>To reduce risk at a minimum of attackers from stealing, recompiling, until publishing back to the store again but with extra profit elements, such as ads, R8’s obfuscation feature does its best to transform any reverse engineering activity much more difficult starting at a point. We can enable R8 via app-level build.gradle file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2217ae343d547d97fee8f9ca837d91b6/href">https://medium.com/media/2217ae343d547d97fee8f9ca837d91b6/href</a></iframe><p>Now an example, let’s compare the decompiled source code between the one which doesn’t benefit the R8 and the one with R8 enabled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fe73d8bd469e3b72b952baf9dd49f89/href">https://medium.com/media/2fe73d8bd469e3b72b952baf9dd49f89/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/521b7d6ae9242acc86a399ef105362d0/href">https://medium.com/media/521b7d6ae9242acc86a399ef105362d0/href</a></iframe><p>Though it’s harder to read now, still, the essences of the source code, like the security schemes that we’re using, AES256_GCM_SPEC or AES256_GCM_HKDF_4KB can still be clearly spotted at the respective <strong>31st</strong> and <strong>37th</strong> lines which is not good enough. Now let’s look over the one with R8 enabled:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c617d67a488eda66893207498acb218f/href">https://medium.com/media/c617d67a488eda66893207498acb218f/href</a></iframe><p>No, I’m not pasting the wrong gist. What we’re seeing is valid and I do not say the code is really getting deleted by the R8 but more like it’s obfuscated and inlined to somewhere entry point classes where the invocation of the instance happens, e.g., MainActivity.</p><p>This new decompiled project structure should make any tracing-based process from a given APK/AAB becomes one step harder. Strictly speaking,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*6J3ZPSiQoVa8KbcFZpO_Sw.jpeg" /><figcaption>Boromir from LOTR</figcaption></figure><blockquote>Note: dex2jar and JD-GUI tools are used to generate above decompiled source code.</blockquote><h3>Use Case</h3><p>Last but not least, this writing also brings some daily use cases (based on experience) to the surface that we might want to put great attention on securing them.</p><h4>Google Cloud API Keys</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c70e576d4e3968dba11671ff088392/href">https://medium.com/media/e9c70e576d4e3968dba11671ff088392/href</a></iframe><p>If we integrate some google cloud services, then we probably have this secret API key, and no matter what, we will want to protect the key in a VERY secure way, else the billing will just blow up.</p><p>There are numerous ways we can store the key, like storing it in a C/C++ file <a href="https://medium.com/programming-lite/securing-api-keys-in-android-app-using-ndk-native-development-kit-7aaa6c0176be">using NDK</a>⁴ in the first place or hosting own service provider to keep it. The rest is optional if we welcome JetSec’s EncryptedSharedPreferences for an easier accessing benefit with some security guarantees. We could also add an extra security layer by taking advantage of the GCP’s key restrictions feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AiPuvGChd81fR2yeHchDBQ.png" /><figcaption>Google Cloud Platform (GCP) key restrictions</figcaption></figure><p>Lock which platforms can make the requests, fill up the forms, and we can sit relaxed for a moment in case the key leaks.</p><h4>Google Cloud Service Accounts</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f3ec6c75d104f7c7d1cb51af52ba39b/href">https://medium.com/media/0f3ec6c75d104f7c7d1cb51af52ba39b/href</a></iframe><p>This credential is literally an alternative to the previous GCP API keys. As far I can state, certain GCP services, like Translation API, require this credential parameter for some advanced auth ops.</p><p>Same rule as previous, we want to store the JSON first to some trusted mediums where we favor one and having the JetSec’s EncryptedFile which is a better candidate for securing this credential type in advance.</p><h4>Firebase’s google-services.json</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ea6af93f32f77a5136a626356201198/href">https://medium.com/media/4ea6af93f32f77a5136a626356201198/href</a></iframe><blockquote>FAQ:</blockquote><blockquote>“Hold on a sec… Are you saying we could secure the JSON as well? We just follow every instruction as stated (below) and let the system do the rest for the Firebase initialization.“</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*PaqWStruqEkl6Z9quODNnA.png" /><figcaption>Firebase integration steps</figcaption></figure><p>Well, before I’m about to answer <strong>“Yes”</strong> o̶r̶ ̶<strong>”̶N̶o̶”</strong>̶, let me show you <strong>what could go wrong</strong> afterward by the above integration steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpskqPrR0PKktAcp2RRzUg.png" /><figcaption>Exposed firebase project information</figcaption></figure><p>So when someone has the APK and decompiles back, we can see the resources.arsc file exposes every embedded resource including our firebase credential information. Judging by this issue, well, in all respects, I personally wouldn’t recommend by following the “official” documented for the firebase integration.</p><p>Instead, we could do some hacks by extracting the JSON fields, variablizing them, then we can initialize the Firebase manually. Here’s how:</p><ul><li>Don’t remove com.google.gms.google-services plugin that has been set by us in app-level build.gradle. We need it to extract the fields.</li><li>Run ./gradlew :app:assembleDebug (at least in MacOs) in terminal or via <strong>Gradle</strong> tab &gt; <strong>[project_name]</strong> &gt; <strong>app</strong> &gt; <strong>Tasks</strong> &gt; <strong>other</strong> &gt; <strong>assembleDebug</strong> to extract the fields.</li><li>Now we can remove the plugin along the classpath &quot;com.google.gms:google-services:$whatever_version&quot; set in project-level build.gradle.</li><li>The extracted result is mapped to an XML file as shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU1tdNtf7PsIud2g6YHNVw.png" /><figcaption>Located in: ../app/build/generated/res/google-services/debug/values/values.xml</figcaption></figure><ul><li>Copy them and we can initialize the firebase manually.</li></ul><blockquote>Note: By owning these constants, now we can store somewhere and secure them with any fitted security tool we have mastered.</blockquote><h3>Closing</h3><p>Thanks for reaching the potato. Few words left by this great said:</p><blockquote>“Security is always excessive until it’s not enough.”<br>- Robbie Sinclair</blockquote><p>In the security world, I believe, there’s no such single tool, silver bullet solution that automatically puts us in the green zone. Great security can only be achieved with a broad collection of complementary tools, every considered security element is taken into account, that forms a layered defense. <em>A layered defense is the only viable defense.</em></p><p>That’s all about. Hope this helps, thanks.</p><p>External links:</p><ol><li><a href="https://developer.android.com/training/articles/keystore">https://developer.android.com/training/articles/keystore</a></li><li><a href="https://developer.android.com/topic/security/data">https://developer.android.com/topic/security/data</a></li><li><a href="https://www.infoworld.com/article/2076237/signed-and-sealed-objects-deliver-secure-serialized-content.html">https://www.infoworld.com/article/2076237/signed-and-sealed-objects-deliver-secure-serialized-content.html</a></li><li><a href="https://medium.com/programming-lite/securing-api-keys-in-android-app-using-ndk-native-development-kit-7aaa6c0176be">https://medium.com/programming-lite/securing-api-keys-in-android-app-using-ndk-native-development-kit-7aaa6c0176be</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84796824cea" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/modern-android-security-development-f84796824cea">Modern Android Security Development</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[Coroutine Task Executor]]></title>
            <link>https://proandroiddev.com/coroutine-task-executor-916febd5c460?source=rss-ac79e61882e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/916febd5c460</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Erick Sumargo]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 15:59:13 GMT</pubDate>
            <atom:updated>2020-09-13T14:02:03.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dndBE2W_jYejuVQ9q-Jxw.png" /></figure><p>Featured in <strong>Kotlin Weekly</strong> - Issue #214:</p><p><a href="https://mailchi.mp/kotlinweekly/kotlin-weekly-214">Kotlin Weekly #214</a></p><p>Since Kotlin is officially favored for Android development, we try to get to know what coroutine is and how it benefits us writing asynchronous code but in a sequential manner. Coroutine also emits its standardization figure where we are no longer faced with some of old school async approaches, e.g., Thread, Handler, or AsyncTask <a href="https://developer.android.com/reference/android/os/AsyncTask">(So long, partner ~)</a>².</p><h3>Introductory</h3><p>Some may use coroutine in quite trivial needs like one-shot task, dispatching some heavy tasks to the background, and returning the result afterward, once each time it’s invoked. When complexity grows, however, there might be a need for how we can manage the ongoing coroutine task or the one to be executed in some specific situations.</p><p>Introducing the <strong>Executor</strong> of coroutine tasks <strong>(opinionated naming)</strong>. One may interpret it as the one who will be managing the coroutine’s task. Executor is nothing but a bunch of abstracted basic patterns that we can make use of according to some specific needs without having the codebase getting cluttered by some of relative complex states.</p><p>To get more real picture, say whenever there is a newer API request, we want to cancel the ongoing coroutine which holds the previous request so that we don’t need to handle the incoming obsolete response (whatever the actual reason is). Therefore, the executor will abstract the work for us.</p><p>Below are defined executor types along with some of their use cases:</p><h4><strong>ConflatedExecutor</strong></h4><p>This type resembles the case I’ve introduced at glance previously. Imagine we’re developing a translator app and whenever the user is getting back to typing after stopping for some time millis, we would want to drop some ongoing previous API requests so that the app preserves the loading state instead of having last obsolete response shown up while the latest query has just been requested. This may cause ambiguity for the displayed translated result. Hence, we could assign this type to do the work since:</p><blockquote>ConflatedExecutor cancels any ongoing coroutine task and executes the latest one.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c99b2580c6a20f78220c35753695288/href">https://medium.com/media/8c99b2580c6a20f78220c35753695288/href</a></iframe><p>Now let’s magnify of what each line does:</p><p>2nd<br>Since we want to be capable of canceling any ongoing active task, we load the task inside another child coroutine. Hence, it results Job.</p><p>We also wrap the Job with <a href="https://www.baeldung.com/java-atomic-variables">Atomic</a>³ stuff since it benefits us for thread-safe: any updates made will be visible to other threads since they fetch from the memory.</p><p>5th<br>Create the coroutine scope where we want to launch a new coroutine inside.</p><p>6th<br>Create a new coroutine, in this case, using async to create one since we want to return a value from the delegated task. We also want to start the coroutine <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-l-a-z-y.html">LAZY</a>⁴-ly to ensure any previous active coroutine gets canceled first.</p><p>8th<br>This block gets invoked every time when an associated job completes or canceled. At this state, we should zero-out the atomic activeTask back once it’s no longer needed. <a href="http://man.hubwiz.com/docset/Kotlin.docset/Contents/Resources/Documents/api/latest/jvm/stdlib/kotlin.native.concurrent/-atomic-reference/index.html">Otherwise, memory leak could happen.</a>⁵</p><p>14th<br>Here we’re working with an aggressive tight loop to check if any active task/coroutine is ongoing. If none, we have the activeTask memorized the latest task.</p><p>15th<br>If there’s any, we want to cancel them <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/cancel-and-join.html"><strong>completely</strong></a>⁶ and avoid a possible tight loop on a single thread by <a href="https://www.lukaslechner.com/how-to-run-an-expensive-calculation-with-kotlin-coroutines-on-the-android-main-thread-without-freezing-the-ui/">yield</a>⁷-ing on <strong>15th.</strong></p><p>18th<br>After every ongoing task is canceled, now we can start the delayed coroutine and await for the promised result.</p><h4>QueueExecutor</h4><p>As the name implies, assume we’re doing a messaging app. Every time we tap the UI send button, it posts our message to an instance of what is called the <em>“Message Broker”</em> or similar ones to be processed in advance. In order guaranteeing the messages are posted in order (covering the case where the user presses the button in real quick), we want to assign the work for this type as:</p><blockquote>QueueExecutor will just queue up every incoming coroutine task and execute them FIFO-ly.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36b410c8778daa7f9aa886f161542401/href">https://medium.com/media/36b410c8778daa7f9aa886f161542401/href</a></iframe><p>Take notes for the special concurrency type w̶h̶i̶c̶h̶ ̶y̶o̶u̶ ̶p̶r̶o̶b̶a̶b̶l̶y̶ ̶m̶i̶g̶h̶t̶ ̶h̶a̶v̶e̶n̶’̶t̶ ̶s̶e̶e̶n̶: the <strong>Mutex.</strong></p><p>2nd<br>If we are previously familiar with synchronized or ReentrantLock, Coroutine’s alternative would be <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/">Mutex</a>⁸. Mutex resembles just like a key where an instance needs to acquire it to enter the block. This guarantees only one request runs at a time.</p><p>5th<br>Instead of defining manually</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/669271e1e421139ab5450ac17be9f9c7/href">https://medium.com/media/669271e1e421139ab5450ac17be9f9c7/href</a></iframe><p>The extension withLock has already abstracted those clauses away. At this state, the coroutines are lining up and in <strong>suspended</strong> state.</p><p>6th<strong><br></strong>Now we have the key (we’re inside the block), time to execute the delegated task.</p><blockquote>Note: Upon block completion by unlocking back the mutex, the key shall be passed to next inlined coroutine.</blockquote><h4>ConcurrentExecutor</h4><p>Nothing more but our typical daily practice.</p><blockquote>ConcurrentExecutor will just keep firing-up the coroutine tasks in parallel.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec945aae03a0ee8ae02e0620e9619bf9/href">https://medium.com/media/ec945aae03a0ee8ae02e0620e9619bf9/href</a></iframe><p>(Nothing fancy to be explained 😎)</p><h3>The Aggregator</h3><p>Regarding the above executor types, shouldn’t we need to reimport those related types every time we jump into similar use cases?</p><p>Well reflecting from personal practice, aggregating them into a central executor class will save the day. This central will then act as the dispatcher, assigning to which executor type based on a set of schemas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d83447bad0072405a8b9e6f64504094e/href">https://medium.com/media/d83447bad0072405a8b9e6f64504094e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1dd083247fb57e298fd3a0d3edaecbb/href">https://medium.com/media/d1dd083247fb57e298fd3a0d3edaecbb/href</a></iframe><p>Yet we’re much easier appending when there are other new executor types, clients can still keep their business side clean by only interacting with the single aggregator’s execute API. Just delegate the task and select which schema for how one would like the task is getting executed.</p><h3>Sum Up,</h3><p>Having this executor concept could offer <a href="https://github.com/ErickSumargo/Kirin">codebase a strong foundation</a>¹ on how we want to control the coroutine task execution in some advanced ways. Those above-mentioned 3 types are just the starter pack to begin with and the companion aggregator provides us with a scalable space whenever there are other existing variants we want to enrich with.</p><p>Alright, sharing is caring. Let’s share what other schemas you might have sparked with or if you have related questions, just leave the comments below. You can also view this sample project to give you more visual of each executor’s specialty. Thanks, hope this helps.</p><p><a href="https://github.com/ErickSumargo/Executor-Demo">ErickSumargo/Executor-Demo</a></p><p>External links:</p><ol><li><a href="https://github.com/ErickSumargo/Kirin">https://github.com/ErickSumargo/Kirin</a></li><li><a href="https://developer.android.com/reference/android/os/AsyncTask?authuser=1">https://developer.android.com/reference/android/os/AsyncTask</a></li><li><a href="https://www.baeldung.com/java-atomic-variables">https://www.baeldung.com/java-atomic-variables</a></li><li><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-l-a-z-y.html">https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-l-a-z-y.html</a></li><li><a href="http://man.hubwiz.com/docset/Kotlin.docset/Contents/Resources/Documents/api/latest/jvm/stdlib/kotlin.native.concurrent/-atomic-reference/index.html">http://man.hubwiz.com/docset/Kotlin.docset/Contents/Resources/Documents/api/latest/jvm/stdlib/kotlin.native.concurrent/-atomic-reference/index.html</a></li><li><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/cancel-and-join.html">https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/cancel-and-join.html</a></li><li><a href="https://www.lukaslechner.com/how-to-run-an-expensive-calculation-with-kotlin-coroutines-on-the-android-main-thread-without-freezing-the-ui/">https://www.lukaslechner.com/how-to-run-an-expensive-calculation-with-kotlin-coroutines-on-the-android-main-thread-without-freezing-the-ui/</a></li><li><a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/">https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916febd5c460" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/coroutine-task-executor-916febd5c460">Coroutine Task Executor</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>