<?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 Brian Yencho on Medium]]></title>
        <description><![CDATA[Stories by Brian Yencho on Medium]]></description>
        <link>https://medium.com/@brianyencho?source=rss-2f3d9e7b8db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U8u1tT3KbJ4LcPd3ZobDQw.jpeg</url>
            <title>Stories by Brian Yencho on Medium</title>
            <link>https://medium.com/@brianyencho?source=rss-2f3d9e7b8db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:01:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brianyencho/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[Lies, Damn Lies, and Semantic Versioning]]></title>
            <link>https://medium.com/livefront/lies-damn-lies-and-semantic-versioning-2b6bc98ccff4?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b6bc98ccff4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Thu, 08 Jan 2026 22:20:37 GMT</pubDate>
            <atom:updated>2026-01-08T22:20:37.456Z</atom:updated>
            <content:encoded><![CDATA[<h4>Semantic versioning is great…when used properly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*53UKXfE23BPf7gzA0Fahvg.png" /></figure><p>You may have been in a meeting like this before: your team has created a new open source project or internal library that you’d like to distribute and the question then comes up about how to assign meaningful version numbers to its future releases.</p><p>“Well, obviously we’ll use semantic versioning,” someone will say and everyone agrees. Not only does it seem like the clear choice, it can seem like the <em>only</em> choice. But is it really?</p><p>Semantic versioning is an excellent scheme and one that I’ve taken advantage of numerous times, but I also believe it to be a common tool that is widely misused and misunderstood (just like how that drawer under your oven is <a href="https://www.thekitchn.com/here-s-what-that-drawer-under-your-oven-is-actually-for-254577">not actually meant for storing your cookie sheets and baking pans</a>).</p><p>Before we discuss these issues, though, let’s first dive a little deeper into what semantic versioning actually is.</p><h3>One Scheme To Rule Them All</h3><p>Created around 2011 by GitHub cofounder Tom Preston-Werner, semantic versioning is a clearly defined and well-documented scheme that is meant to standardize the way external dependencies are versioned in order to easily communicate at a glance the <em>kinds</em> of changes present in each release. It’s an admirable goal and, if anything, it has had a great influence over how dependency versions typically <em>look</em>.</p><p>Details of the 2.0.0 version of the scheme — because yes, semantic versioning is itself semantically versioned — can be found in its <a href="https://semver.org/spec/v2.0.0.html">online specification</a> and include the following high-level summary:</p><blockquote>Given a version number MAJOR.MINOR.PATCH, increment the:</blockquote><blockquote>1. MAJOR version when you make incompatible API changes<br>2. MINOR version when you add functionality in a backward compatible manner<br>3. PATCH version when you make backward compatible bug fixes</blockquote><p>To put this a little more visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpvA1Cox9VcPPiyoTB17ww.png" /></figure><p>Seems easy enough, right? If the MAJOR version does not change, you should be good to pull in any updates you want in order to get new features and bug fixes, without fear of introducing backwards-incompatible changes to your application that may require significant time of your own to address.</p><p>The problem is that this is not always how it works out. To see why, we need to dig a little deeper into how the first number of this triplet actually works.</p><h3>Let’s Talk About Breaking Changes</h3><p>When you look further into the specification for how the MAJOR version behaves, you will find the following description:</p><blockquote>Major version X (X.y.z | X &gt; 0) MUST be incremented if any backward incompatible changes are introduced to the public API. It MAY also include minor and patch level changes. Patch and minor versions MUST be reset to 0 when major version is incremented.</blockquote><p>Note the emphasis on the word “MUST” there when describing backward incompatible changes, also typically known as “breaking changes”. It is <strong><em>not optional</em></strong> to increment the MAJOR version when it includes these kinds of changes.</p><p>What exactly defines these incompatible, breaking changes, though? Unfortunately, the specification does not explicitly categorize these. While some libraries tie these to concepts like <a href="https://en.wikipedia.org/wiki/Binary-code_compatibility">binary-</a>/<a href="https://en.wikipedia.org/wiki/Source-code_compatibility">source-code compatibility</a>, let’s use a definition here that most folks would intuitively agree with:</p><p><strong>“Breaking changes” are any changes made to the exposed, intended surface of a library that COULD require changes by SOME consumers of it in order for it to continue working correctly after updating.</strong></p><p>The maintainers of the semantic versioning scheme will <a href="https://semver.org/#if-even-the-tiniest-backward-incompatible-changes-to-the-public-api-require-a-major-version-bump-wont-i-end-up-at-version-4200-very-rapidly">readily admit</a> that a key purpose of it is to discourage these kinds of changes and to motivate developers to find ways to introduce changes in a backwards-compatible way. In many cases, though, the actual effect has been to discourage folks from incrementing the MAJOR version, despite the changes included. Let’s see why.</p><h4>The Obvious Breaking Changes</h4><p>First, let’s look at some changes that anyone would unambiguously recognize as breaking.</p><p>Consider the following function call in the Kotlin language.</p><pre>suspend fun submitPayment(<br>    paymentAmountDollars: Long<br>) {<br>    // ...<br>}</pre><p>Kotlin is a <a href="https://kotlinlang.org/docs/null-safety.html">null-safe language</a> and this function therefore has a single strictly-required parameter, paymentAmountDollars. What would happen if all of a sudden we needed an additional required parameter, paymentDescription? This would result in the following:</p><pre>suspend fun submitPayment(<br>    paymentAmountDollars: Long,<br>    paymentDescription: String<br>) {<br>    // ...<br>}</pre><p>This, of course, is a classic breaking change, as any existing consumers would need to update all of their calls to include a value for this new parameter.</p><p>The maintainer of such a library might try to avoid these kinds of breaking changes by making the new parameter <em>optional</em> in some way. Here, for example, we could make paymentDescription nullable and provide a default value of null:</p><pre>suspend fun submitPayment(<br>    paymentAmountDollars: Long,<br>    paymentDescription: String? = null<br>) {<br>    // ...<br>}</pre><p>Assuming a null value is possible within the internal constraints of the feature, this nicely adds new functionality without <em>requiring </em>immediate changes by consumers.</p><p>These are the kinds of changes that semantic versioning handles well and which library maintainers tend to do a great job of correctly identifying — in this case by incrementing the MINOR version (going from, say, 1.2.3 to 1.3.0). But let’s look at a class of changes that are <em>not</em> so obvious.</p><h4>The Non-Obvious Breaking Changes</h4><p>To see where more subtle changes come in, let’s consider adding a return type to our function from above:</p><pre>suspend fun submitPayment(<br>    paymentAmountDollars: Long,<br>    paymentDescription: String? = null<br>): PaymentReceipt {<br>    // ...<br>}</pre><p>where our PaymentReceipt model includes all of the original data passed in plus an identifier, paymentId :</p><pre>data class PaymentReceipt(<br>    val paymentId: String,<br>    val paymentAmountDollars: Long,<br>    val paymentDescription: String?<br>)</pre><p>Suppose this PaymentReceipt model is <em>only</em> ever used from the library as a return type. What happens if we want to add a new required property to our model, createdAtMillis:</p><pre>data class PaymentReceipt(<br>    val paymentId: String,<br>    val paymentAmountDollars: Long,<br>    val paymentDescription: String?<br>    val createdAtMillis: Long<br>)</pre><p><strong>This would constitute a breaking change</strong>. Even though you are only adding data to a response model and consumers are not required to use that data in any way, the model is part of the API contract and this change is backwards incompatible.</p><p>To see why, consider any time a consumer might be manually creating that object. Any previous calls like</p><pre>val receipt = PaymentReceipt(<br>   paymentId = paymentId,<br>   paymentAmountDollars = paymentAmountDollars,<br>   paymentDescription = paymentDescription<br>)</pre><p>would no longer compile with the latest updates. This may seem contrived for a “response” model but this could be done in order to create mock data for tests or elsewhere, or could even be the result of deserializing this data from a database.</p><p>You also would not want to use the “trick” of providing this new property as an optional value just for the sake of backwards compatibility, like so:</p><pre>data class PaymentReceipt(<br>    val paymentId: String,<br>    val paymentAmountDollars: Long,<br>    val paymentDescription: String?<br>    val createdAtMillis: Long? = null // Not what you want!<br>)</pre><p>This is because this would no longer be communicating the intent of the model change, which is to say that you will <em>always</em> be given the createdAtMillis data in your response.</p><p>Similar problems arise when adding new cases to an enum for example. If you begin with the following:</p><pre>enum class PaymentType {<br>    Amex,<br>    Visa<br>}</pre><p>and then add one more case, MasterCard, in a future release:</p><pre>enum class PaymentType {<br>    Amex,<br>    Visa,<br>    MasterCard<br>}</pre><p>you have now broken any consumers that might be exhaustively checking for all cases of PaymentType.</p><p>These are just some of the many subtle ways that small changes that don’t immediately seem like they would introduce incompatibilities to consumers actually do.</p><h3>Major Versions, Major Problems</h3><p>The question is then: how should we increment the version number for these kinds of changes? They are clearly of the breaking variety, so we <em>should</em> update the MAJOR version. But sometimes these and other kinds of seemingly minor changes either escape the notice of the developers or they just don’t <em>feel</em> right: to many people, “major” version updates should include <em>major</em> changes. So what happens is that breaking changes just…slip into minor versions.</p><p>A <a href="https://repository.tudelft.nl/record/uuid:57a68419-8c92-445f-9c23-0fb36ece0cde">study</a> from several years ago found that roughly a <strong>third of libraries </strong>hosted on Maven that seemingly adhere to semantic versioning incorrectly include breaking changes in a minor version update. This phenomenon is not limited to small libraries maintained by a single developer in their spare time, either: developers have complained about changes to tools like <a href="https://news.ycombinator.com/item?id=38800707">Python</a>, <a href="https://github.com/apollographql/apollo-ios/issues/3087">Apollo iOS</a>, and <a href="https://github.com/storybookjs/storybook/issues/16837">Storybook</a>.</p><h3>So What Can We Do About It?</h3><p>Library versions should be used with intention to communicate to consumers what to expect, but as we’ve just seen sometimes that can go awry. Here are a few things to keep in mind in order to be successful.</p><h4>Document Your Versioning Scheme</h4><p>As the maintainer of a library, the first thing to note is that you should <strong>always document what kind of versioning scheme you are using</strong>, whatever it may be. When confronted with a version of the format MAJOR.MINOR.PATCH, many developers will simply assume this means semantic versioning is being followed, even though that’s not always the case. Describe your chosen scheme and its rules directly in the README of your project or include a link there to where that definition can be found.</p><h4>Be Honest</h4><p>Next, to quote one of the world’s most famous former soccer players: <a href="https://www.youtube.com/watch?v=3E4s0RqCBzU">Be honest</a>. Once you’ve defined your scheme, make sure you are actually sticking to it.</p><p>In the case of semantic versioning, this means (among other things) either being extremely careful not to include breaking changes in minor versions or just accepting that MAJOR versions <a href="https://tom.preston-werner.com/2022/05/23/major-version-numbers-are-not-sacred">“are not sacred”</a>, to quote Tom Preston-Werner. Large and frequently changing MAJOR version numbers are just fine and don’t need to signify a “major release” in the traditional sense.</p><p>This is particularly important when providing your dependency via package managers like <a href="https://en.wikipedia.org/wiki/Npm">NPM</a> and <a href="https://github.com/rust-lang/cargo">Rust Cargo</a> that strictly require semantic versioning in order to safely manage <a href="https://en.wikipedia.org/wiki/Transitive_dependency">transitive dependencies</a>.</p><h4>Use What Works Best For You</h4><p>Most important, though, is to use what works best for you and your team. And, where possible, that may mean <strong>not</strong> choosing semantic versioning.</p><p>For example, the Rust language <a href="https://rust-lang.github.io/rfcs/1105-api-evolution.html#detailed-design">defines its own scheme</a> that is very similar to semantic versioning but declares that new public items do <em>not</em> require a MAJOR version bump. Android’s Jetpack libraries <a href="https://developer.android.com/jetpack/androidx/versions">declare</a> that the rules of semantic versioning are used to indicate <em>binary compatibility only </em>and that minor releases may include breaking changes as far as <em>source compatibility</em> goes. And TypeScript is <a href="https://www.learningtypescript.com/articles/why-typescript-doesnt-follow-strict-semantic-versioning">versioned with a scheme</a> that bumps the MINOR version on a roughly quarterly basis (no matter what changes are included) and increments the MAJOR version simply to avoid the MINOR value going above 9 (¯\_(ツ)_/¯).</p><p>In my own experience of creating libraries, I’ve found semantic versioning to be very useful when applied to more focused libraries with small, stable API surfaces, but I have leaned more on custom schemes for larger, more dynamic projects, particularly when they involve the modeling of a lot of “data”.</p><p>In one case, we were building a networking library that wrapped hundreds of API calls. Each weekly release would inevitably include additional properties added to some of the response models, so by the terms of semantic versioning we would only ever be incrementing the MAJOR version week-by-week. We decided instead on a scheme of the MAJOR.MINOR.PATCH format, but where:</p><ul><li>The MAJOR version was only incremented to indicate fundamental overall changes in the library (ex: moving from RxJava 1 to RxJava 2 as a means of handling asynchronous functionality).</li><li>The MINOR version was incremented with each weekly release and the corresponding CHANGELOG entries clearly indicated which changes fell into each of the following buckets: breaking changes and non-breaking API changes, behavior changes, and bug fixes.</li><li>The PATCH version was only incremented when releasing a “hotfix”, which was a build based directly off of a previously weekly release. This allowed for fixes to be included for some consumers before their own deployments without forcing them to pull in all the other changes from subsequent weekly releases.</li></ul><p>In each case, our schemes were chosen to best convey the relevant and necessary information to our consumers.</p><h4>And Speaking Of Consumers</h4><p>Finally, as a consumer of library dependencies, always <a href="https://en.wikipedia.org/wiki/RTFM">“read the manual”</a>: don’t make assumptions about how releases work for any given project. Check to see what versioning scheme is used and <strong>always read the CHANGELOG</strong> to see what you are actually pulling in. Among other things, you may find that there are more breaking changes than you would have initially thought and you will have to adjust your plans accordingly.</p><h3>Final Thoughts</h3><p>With all things in software engineering, communication is paramount. Semantic versioning is a great tool, but it may not always be the <strong>best </strong>one to effectively deliver information from one team to another. Rather than defaulting to a seemingly ubiquitous standard, make sure to find the right fit for you and what you are building.</p><p><em>Brian works at </em><a href="https://livefront.com/"><em>Livefront</em></a><em>, where he fixes bugs, adds new functionality, and makes the occasional breaking change or two.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b6bc98ccff4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/lies-damn-lies-and-semantic-versioning-2b6bc98ccff4">Lies, Damn Lies, and Semantic Versioning</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Barack Obama’s Wardrobe Has in Common With a Good Git History]]></title>
            <link>https://medium.com/livefront/what-barack-obamas-wardrobe-has-in-common-with-a-good-git-history-579782dc3af7?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/579782dc3af7</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 16:02:01 GMT</pubDate>
            <atom:updated>2023-10-26T14:27:59.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWLZgmxf7pv8pdSTw03zSw.png" /></figure><p>One summer day in the late August heat of 2014, then-President Barack Obama made a decision that would shock the nation: he wore a different suit. The resulting “<a href="https://en.wikipedia.org/wiki/Obama_tan_suit_controversy">tan suit controversy</a>” dominated a news cycle and spread for a variety of reasons, but ultimately it was triggered by the novelty of the suit itself. Like Steve Jobs’ black turtlenecks and Mark Zuckerberg’s gray shirts, Obama typically stuck with the same <a href="https://www.fastcompany.com/3026265/always-wear-the-same-suit-obamas-presidential-productivity-secrets">blue or gray suits</a> each day.</p><p>The common denominator behind this shared behavior is the psychological concept of <a href="https://en.wikipedia.org/wiki/Decision_fatigue">decision fatigue</a>: that even the smallest decisions we make each day can drain the finite amount of brainpower we have to make decisions and to make them well. A strategy taken by these individuals to preserve this precious resource is to eliminate as many minor decisions as possible: wear the same things, eat the same things, follow the same schedule, and so on. This allows you to focus your mental energy on the decisions that really matter.</p><p>So what does this all have to do with everyone’s favorite version control system, git? As with so much in programming, there is no “right” way to structure a git commit or manage the git history of a project; you must simply choose a guiding principle and organize your patterns around it. I personally believe in choosing a strategy that reduces decision fatigue (and “mental fatigue” more broadly) for all the various “consumers” of a commit. I will go into more detail about <em>how </em>to do this below (and feel free to just skip to that numbered list if you’d like) but I think it’s very important to first address <em>why </em>I believe this. And we need to start with who a commit is actually for.</p><h3>Whose History Is It?</h3><p>It must be emphasized that over the course of an average project’s entire lifecycle, the number of people viewing a commit that did <em>not</em> write it will far outnumber those that did. These other people will also have the least intimate knowledge of what a commit is actually for and how it is intended to work. As a practical matter, then, building a good git history should really be for <em>them</em>. And, given enough time, even code you wrote yourself can someday appear foreign to you. So keeping a good history can help your future self as well.</p><p>Bearing this in mind, it’s worth noting that there are two broad categories of people that will, at some point, view a particular commit:</p><ol><li><strong>Code Reviewers</strong><br>Those viewing the commit <strong><em>before</em></strong> it is merged into the history through the process of code review.<strong> </strong>These people are generally known as “code reviewers”. On a good team, everyone will, at some point, be a code reviewer and there may be multiple for each set of new code changes.</li><li><strong>Code Detectives<br></strong>Those viewing the commit <strong><em>after</em></strong> it has been merged.<strong> </strong>These are typically individuals that are going back through the history to try and understand why something was added or when a bug was introduced. For lack of a better name I will call these people “code detectives” to distinguish them from the folks above.</li></ol><p>The job of a code reviewer is roughly to ensure that the code does what it says it does and does not introduce any unintended and undesirable side effects. Crucially, they have an opportunity to make suggestions to improve the code before it becomes history and serve as the first line of defense in preventing mistakes from entering the project’s code base. In order to do these things well, though, they first have to be able to <em>completely understand code that they did not write</em>. Even with the ability to discuss the code with the author, this type of exercise can be very mentally taxing.</p><p>Code detectives have all these same challenges in addition to others: they may not always know what they are looking for and even when they find it, they may be lacking vital context for understanding it. Many times they do not even have the benefit of being able to talk with the original author of the code. For this reason, a large part of what a code detective does is to try and <em>infer the intention</em> of existing code without actually being able to ask about it or follow up on their suspicions.</p><p>The jobs of these two groups are slightly different but at their core they both involve a series of decisions that must be made, line by line, to answer the ultimate question: <em>what does this code even do?</em> Depending on how the commits are structured by the author, this can either be relatively straightforward or a painful slog with unnecessary roadblocks and red herrings.</p><h3>Decisions, Decisions</h3><p>Let’s now consider what kinds of decisions go into understanding a commit. First we need to note that each line of a commit can be categorized as one of two things: an “added” line of code or a “removed” one.</p><p>Without any additional context, the following decisions must be made when viewing a single line of “added” code:</p><ol><li>Is this an entirely new line of code?</li><li>If it is <strong>not</strong> a new line of code, is it an existing line of code that has simply been moved from somewhere else?</li><li>If it is <strong>not</strong> a new line of code and it has <strong>not</strong> been moved, is it a trivial modification of an existing line (such as a formatting change) or is it a legitimate logical change?</li><li>If it is either an entirely new line of code or a modification that leads to a logical change, why is it being done? Is it done correctly? Can it be simplified or improved?</li></ol><p>Note that the final point is really the “meat” of understanding the commit and the first three points are much more trivial but still entirely necessary decisions that must be made in order to reach this point.</p><p>We can see a similar process for each “removed” line of code:</p><ol><li>Is this line being removed entirely?</li><li>If it is <strong>not</strong> being removed entirely, is it being moved or modified?</li><li>If it is <strong>not </strong>being removed entirely and it is <strong>not</strong> just being moved, is it the result of a trivial modification (ex: formatting) or the result of a logical change?</li><li>If it is in fact a logical modification, why is it being modified? Is it being done correctly?</li><li>If the line is being removed entirely, why is it no longer needed?</li></ol><p>Once again, the final two points are what really matter.</p><p>So this finally brings us back to decision fatigue:</p><blockquote><strong>How can we organize commits so that we eliminate these first few trivial choices and allow viewers to focus on the important ones?</strong></blockquote><p>You don’t want your team spending their limited brain power and time deciding, for example, that some chunk of code was just moved from one module to another without modification and then miss the coding mistakes present in the actual new code. Multiply this across teams at a big organization and this can add up to a measurable loss of productivity.</p><p>So, now that we’ve discussed <em>why</em> I believe we should follow this strategy, let’s finally discuss <em>how</em> I advocate for putting it into practice.</p><h3>1. Place trivial modifications in their own commits</h3><p>The simplest and most important thing to do is to separate trivial modifications out into their own commits. Some examples of this include:</p><ul><li>Code formatting changes</li><li>Function / variable / class renames</li><li>Reordering of functions / variables / imports within a class</li><li>Removing unused code</li><li>Moving file locations</li></ul><p>When placed in their own commits, these kinds of changes do not require much, if any, investigation into their “correctness”. When mixed with other changes, though, they are a huge source of mental drain, forcing you to find the logical pin in the haystack of code churn.</p><p>Consider the following commit mixing trivial changes with non-trivial ones:</p><p><strong>Commit message: “Update valid fruits list”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zVY-VwuknL5_DvSAtnM6Lw.png" /></figure><p>How long did it take you to spot the <em>non-trivial </em>changes? Now see what happens when these two changes are split up into two separate commits:</p><p><strong>Commit message: “Update valid fruit list formatting”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eleyqBfYwJNxUYgSlleN4w.png" /></figure><p><strong>Commit message: “Add dates to valid fruits list”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FsECZnfdNarPmdUVxR4i3w.png" /></figure><p>The “formatting only” commit can essentially be ignored and the code additions can be discovered immediately at a glance.</p><h3>2. Place code refactors in their own commits</h3><p>Code refactors involve changes to some code’s structure but not its function. Sometimes this is done for its own sake but often it is done out of necessity: in order to build upon existing code it is sometimes necessary to first refactor it and it can then be tempting to do both things at once. Mistakes can be made during a refactor, though, and special care is required when reviewing them. By placing this code in its own commit clearly indicated as a refactor, the reviewer knows to flag any deviation from the existing logical behavior as a possible mistake.</p><p>For example, how quickly can you spot the mistake here?</p><p><strong>Commit message: “Update tip logic”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ujmM-U9LfGbXE-P7y7CO-Q.png" /></figure><p>How about now with the refactor split out?</p><p><strong>Commit message: “Extract default tip rate”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cfjObQNhSxQ7i0WQbnzeaA.png" /></figure><p><strong>Commit message: “Allow for custom tip rates”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bAT3j1PA6Sz-9ium7c_VRA.png" /></figure><h3>3. Place bug fixes in their own commits</h3><p>Sometimes in the course of making code changes you notice a bug in the existing code you are seeking to modify or build upon. In the interest of moving forward you may just fix that bug and include it in your otherwise unrelated changes in the same commit. When mixed in this way there are several complications:</p><ul><li>Others viewing this code may not know that there is a bug being fixed.</li><li>Even when it’s known there is a bug fix included, it can be hard to know which code was part of fixing the bug and which was part of the other logical changes.</li></ul><p>Either way, the interpretation of the code becomes more difficult to decipher with these changes mixed together. And as there are many ways to fix a bug, the one that allows your current code changes to move forward may not be the solution to the greater problem caused by the bug and this partial fix may just muddy the waters. These fixes deserve consideration on their own.</p><h3>4. Place separate logical changes in their own commits</h3><p>After splitting out the above types of changes, you should now be left with a single commit with legitimate, logical changes to add / update / remove functionality. For a small, concise change this is often enough. However, sometimes this one commit adds an entirely new feature (with tests) and clocks in at 1000+ lines (or more). Git will not present these changes in a coherent way and successfully understanding this code would require the reviewer to skip around and keep a large fraction of these lines in memory at once to follow along. Along with the decision fatigue involved in processing each line, stretching your working memory in this way is mentally taxing and ultimately inefficient.</p><p>Whenever possible, split up commits based on domains such that each commit independently compiles. This means that the most independent code can be added first, followed by the code that depends on it, and so on. Well-structured code should split up in this way quite naturally, while difficulties found at this stage might hint at larger structural issues like circular dependencies. This exercise may even lead to improvements in the code itself.</p><h3>5. Merge any review changes into the commits they belong to</h3><p>After splitting up your work into several clean commits, you may get review feedback that requires you to make changes to code that appears in one or more of them. Some developers will react to this feedback by adding new commits that address these concerns. The commit list in a given PR might start looking like the following:</p><pre>- &lt;Initial commits&gt;<br>- Respond to review feedback<br>- Work<br>- More work<br>- Addressing more review feedback</pre><p>The first to review this code <em>might</em> find it helpful to see these partial changes but anyone coming late to the party will just end up expending mental energy viewing the original code that is no longer relevant. Therefore, all changes should be merged back into the commits where they belong, as if the code existed that way from the beginning. <a href="https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History">Interactive rebasing</a> is going to be your best friend here. This will then require you to force-push your feature branch back up. This can be tricky and has some costs but there is no reason to fear it! Reviewers will simply need to reset their local copy of your branch (if they have one), and that’s OK.</p><p>The same goes for when a pull request is first opened: each commit should have a purpose and it should not be negated by changes in later commits for all the same reasons mentioned above.</p><p>Consider this initial change followed by several “work” commits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*l8swwyt5UKpS1JRDwNSqSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AKglit_qHl4hsmVNMkSSvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*4oA-Yv4xdlwinZyc8gspGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*IB5Luun9upJBM6ox7bkLKg.png" /></figure><p>Now imagine you are seeing these changes well into the process (or even years later). Wouldn’t you want to just see the following?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DL-2c-RorAsn56G8W18Tbw.png" /></figure><h3>6. Rebase, rebase, rebase!</h3><p>If a feature branch has existed long enough — either because of the time it takes to add the initial code or because of a lengthy code review process — it can start to conflict with changes made on the main branch it was originally based on. There are now two ways to make the feature branch current:</p><ol><li><strong>Merge the main branch into the feature branch. </strong>This will generate a “merge commit” in which all the code changes required to address the conflicts are included. If the feature branch is particularly old, these types of commits may be substantial.</li><li><strong>Rebase the feature branch against the main branch.</strong> The end product here is a new set of commits that act as if they were just created based on the updated main branch. Any conflicts will need to be dealt with as part of the rebasing process but all evidence of the original version of the code will be gone.</li></ol><p>Whenever possible, you should choose the 2nd option: rebasing. Merge commits like this negate all the work done to sort out commits based on the previous steps because all types of changes can be present in a merge commit. And much like the “work” commits described above, they result in wasted mental energy: those looking at the code try to understand how it works, only to find that substantial changes are made in a completely disorganized merge commit.</p><p>If you care about producing a clean history (and you should!), rebasing is the best option here: all changes build off each other in an orderly and linear fashion. You do not need fancy history-viewing tools to understand the relationship between branches.</p><p>Consider the following project history that employs merging between branches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cs6bFYaSx6xlgDePzoyxAQ.png" /><figcaption>Using a merging strategy, rather than a rebasing one, can result in a convoluted history.</figcaption></figure><p>Compare this to a project that rebases all changes and <a href="https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/about-protected-branches#require-linear-history">forbids merge commits even when merging features into the main branch</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tu76iMQpNoXXhQuU4gCug.png" /><figcaption>A project that uses rebasing and completely forbids merge commits appears as a single linear timeline.</figcaption></figure><p>In the former, the relationships between changes must be plotted, pondered, and deciphered; in the latter, you simply flow forward and backward in time.</p><p>Some may argue that it is actually <em>rebasing</em> that destroys history; that you lose the history of changes made to get some code in its final shape before being merged. But this kind of history is rarely useful and is very developer-dependent: one person’s journey may differ from the next, but what matters is seeing a series of commits in the history that reflect the final changes they represent…whatever process it takes to get there. Yes, there are special cases here where merge commits are unavoidable, but they should be the exception. And often the scenarios that cause these (such as long-lived feature branches shared by multiple team members) can be avoided using better work flows (like using feature <em>flags</em> instead of shared feature <em>branches</em>).</p><h3>Counterarguments</h3><p>There are certainly arguments that can be made against this approach and I’ve had plenty of discussions with people who disagree with it. These points are not without merit and as I mentioned at the beginning of the article, there is no one “right” way to structure commits. I want to quickly highlight some points I’ve heard and give my thoughts on each.</p><h4>“Worrying about commit structure so much slows down development.”</h4><p>This is one of the most common points I’ve heard against this approach. It is certainly true that it will take some extra time for the developer writing the code to carefully consider and split up their changes. However, this is also true of any other kind of additional processes that are meant to safeguard against the inherent weaknesses of prioritizing speed and, in the long-run, it might not save the team as a whole any overall time. For example, the argument that development will be slowed is used by teams that do not write unit tests, but these same teams then need to spend more time fixing broken code and manually testing refactors. And, once a team is in the habit of splitting up their changes in this way, the extra time added is greatly reduced because it just becomes part of the normal development process.</p><h4>“My project uses tools that do not even allow for trivial formatting changes.”</h4><p>I agree that this is a great way to minimize the harm that is otherwise caused by formatting-related code churn. As an Android developer, I’m a firm believer in team-wide use of auto-formatters and swear by tools like <a href="https://github.com/pinterest/ktlint">ktlint</a>. However, I also know firsthand from configuring all these tools that they are not perfect and there are plenty of possible formatting changes that they are totally agnostic about. And, as discussed above, some trivial changes are <em>not</em> simply formatting changes, like reordering code. There are always going to be trivial code changes that can be made and therefore there must be a plan for how best to deal with them.</p><h4>“Not all git hosting sites allow Pull Requests with multiple commits.”</h4><p>This is very true! My recommendations are primarily based on using tools like <a href="https://github.com/">GitHub</a> and <a href="https://about.gitlab.com/">GitLab</a> that allow a PR to have as many commits as you’d like, but there are tools such as <a href="https://www.gerritcodereview.com/">Gerrit</a> that do not. In this case, just consider each commit as being its own PR. This does introduce even more overhead for the author (and sometimes for the reviewers) but I believe that in the long-run it is worth the effort. There may even be ways to streamline this process and relate these separate PRs to each other, such as using <a href="https://chromium.googlesource.com/openscreen/+/5fce9d2d907b86fb524c160a06e1ebbc504b1257/advanced_gerrit.md#uploading-a-new-dependent-change">“dependent changes”</a> in Gerrit.</p><h4>“A single commit ensures that all changes compile and pass tests.”</h4><p>This too is a very good point. The automated checks that run on git hosting sites typically only run against the entire set of changes, not for each individual commit. If there is a broken commit along the way that is fixed by later changes, there is no way to automatically detect this. You want each commit to be able to stand on its own in case you someday need to go back and test the state of the code at that point to track down bugs, etc. As an understood rule it should be required for each commit in a multi-commit PR to both compile and pass any relevant tests, but there is no way to strictly enforce this (other than to make each commit its own PR). This requires vigilance but is just something that needs to be weighed against the benefits that come with splitting up the code.</p><h4>“A single commit provides the most context for all the changes.”</h4><p>This one is an interesting point. While git hosting sites like GitHub allow for comments to be added in bulk to a group of commits as part of a PR description, no such thing exists in git itself. This means that the link between commits added in the same PR is not strictly part of the history. Fortunately, sites like GitHub have features that add a link to the PR that produced a commit when viewing it in isolation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jLOaVd0Y7_AspQgcySEUjQ.png" /><figcaption>The #74 here is a link back to the Pull Request that produced this commit, allowing the related commits from the same PR to be viewed.</figcaption></figure><p>While this is not as helpful as having this link in the git history itself, for many projects this is an adequate way to keep track of the relationship between commits.</p><h3>Final Thoughts</h3><p>I hope to have convinced you that splitting code changes into distinct commits of several types has benefits for everyone in the development process:</p><ul><li>It can help the writer improve the structure of the code and better convey the content of the changes.</li><li>It can help code reviewers more quickly review the code and reduce mental fatigue by allowing them to focus their attention on separate, meaningful changes.</li><li>It can help anyone looking back on the code history to find logical changes and bugs more quickly and similarly reduce the mental load that comes with skimming through large amounts of history.</li></ul><p>This is a strategy optimized for <em>teams</em> rather than for <em>individuals </em>and I believe it’s in the best interests of the overall health of a project. Developers may come and go, but git history lives on. Best to make the most of it.</p><p><em>Brian works at </em><a href="https://livefront.com/"><em>Livefront</em></a><em>, where he’s always trying to make just a little more (git) history.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=579782dc3af7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/what-barack-obamas-wardrobe-has-in-common-with-a-good-git-history-579782dc3af7">What Barack Obama’s Wardrobe Has in Common With a Good Git History</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The RxJava Threading Mistake You Are Probably Making]]></title>
            <link>https://medium.com/livefront/the-rxjava-threading-mistake-you-are-probably-making-58ad0579e55?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ad0579e55</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 22:49:54 GMT</pubDate>
            <atom:updated>2024-11-01T14:03:43.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3cE-p05AGu-8YsKjuadzQ.png" /></figure><p><strong>TL;DR: </strong>If you think you completely understand threading in RxJava, take a closer look at the behavior of Processor classes…</p><p>In addition to having a steep learning curve, RxJava has enough secrets to continue to confound developers long after they believe they have mastered it. What follows is one such curiosity related to threading.</p><h3>The Setup</h3><p>Consider the following RxJava call chain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28297488d0c15322a99e77b6c74d71b7/href">https://medium.com/media/28297488d0c15322a99e77b6c74d71b7/href</a></iframe><p>where waitForData and makeNetworkRequestWithData are both functions returning the reactive type Single&lt;T&gt;.</p><p>Now assume the following:</p><ul><li>The project containing this call chain configures network requests (like makeNetworkRequestWithData) so that they run synchronously by default but may be placed on a background thread using subscribeOn. For years this was the default behavior of the RxJava adapters for Retrofit, the most commonly used networking library for Android.</li><li>In this project, all functions returning RxJava types are intentionally configured in a similar way: by default, calls run synchronously and alternative threading may similarly be supplied by callers using the subscribeOn operator.</li><li>Background threading is intended to be supplied by all final callers (the ones ultimately calling subscribe(...)) by adding a subscribeOn call near the end of the chain.</li></ul><p>Given these assumptions, the intention of the above code is to place all code above the subscribeOn(Schedulers.io()) call on an I/O bound thread and all code below the observeOn(AndroidSchedulers.mainThread()) on the main thread of the app process. It is worth noting here that while this is not necessarily a universal setup, it has been a very common one.</p><h3>The Problem</h3><p>This brings us to the point of interest in the setup described above: <em>what </em><em>Scheduler is actually used when making the network request in the example above?</em></p><p>The answer would seem to be clear:<strong> </strong>as intended, this should be determined by the value that has been supplied to the only subscribeOn call in the chain, Schedulers.io().</p><p>In many cases that would be true. There are, however, two key exceptions here and they both depend on the details of the first call in this chain, waitForData:</p><h4>The Violation</h4><p>First, consider a broken assumption. Perhaps this call does not conform to the patterns of the project and it has intentionally applied its own Scheduler such that it runs on and emits on a thread of its choosing. For example, perhaps the call is constructed as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a883bc35b44a641717ab352f2139a3/href">https://medium.com/media/25a883bc35b44a641717ab352f2139a3/href</a></iframe><p>As far as this call is concerned, this subscribeOn(Schedulers.computation()) is all that matters and calculateData will be run on a thread determined by Schedulers.computation(). The emission of the result then happens on that same thread and it forces our network call in question, makeNetworkRequestWithData, to run on this thread as well (and not one based on Schedulers.io() as the code intends).</p><p>The difference here is subtle and will result in a thread meant for heavy computations simply sitting idle while waiting for a network response. While this issue might go unnoticed, it could still be “fixed” by essentially considering this setup a mistake, a violation of the app’s threading patterns. The subscribeOn call here could be removed to bring it into conformity with the rest of the app and the remaining subscribeOn call in the main chain will work as expected.</p><p>The next exception, however, is not so easily addressed.</p><h4>The Surprise</h4><p>What if the call to waitForData was not based on a calculation or a network request, but some manual emission from something like a PublishProcessor? Consider the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ad87b60dec2fbd3e4b6c484550fb905/href">https://medium.com/media/8ad87b60dec2fbd3e4b6c484550fb905/href</a></iframe><p>This code returns a Single&lt;Data&gt; that emits as soon as a value is pushed to the dataProcessor. Note that there are no calls to subscribeOn or observeOn, so this function appears to satisfy the project’s assumptions and <em>should</em> therefore obey the subscribeOn(Schedulers.io()) call of the main chain and ultimately emit on an I/O bound thread.</p><p>There is just one problem: <strong>a </strong><strong>PublishProcessor (or any other kind of </strong><strong>Processor) completely ignores all calls to </strong><strong>subscribeOn</strong>. In fact, from the perspective of a downstream caller there is no good way at all to control the thread a PublishProcessor emits on. This results in all code downstream of a PublishProcessor running on the thread that it emits on until the downstream threading is manually changed with something like a call to observeOn.</p><p>So what thread does a PublishProcessor actually emit on? The answer is simple: on whatever thread values are pushed to it and therefore whatever thread processor.onNext(...) is called on. If you’re looking carefully, this is spelled out in <a href="http://reactivex.io/RxJava/javadoc/io/reactivex/processors/PublishProcessor.html">the documentation</a>:</p><blockquote><strong>Scheduler: <br></strong>PublishProcessor does not operate by default on a particular <a href="http://reactivex.io/RxJava/javadoc/io/reactivex/Scheduler.html">Scheduler</a> and the Subscribers get notified on the thread the respective onXXX methods were invoked.</blockquote><p>This could be a background thread or even the main thread (which can easily happen if the data you are waiting on depends on an OS-level event). In the latter case, the call chain we’ve been discussing would result in a NetworkOnMainThreadException in what would seem like an impossible error. Once this fact is fully absorbed it can seem obvious, but it at first seems to violate our intuition for how operators like subscribeOn are supposed to work.</p><h3>The Resolution</h3><p>Unfortunately, there is no perfect solution to the above problem with the given app constraints. For example, to prevent receiving a NetworkOnMainThreadException, the final subscribeOn call (which is being ignored) could be replaced with the careful use of observeOn or subscribeOn elsewhere. For example, observeOn could be used immediately after the waitForData call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a8bfda6a775c69a50c8a0bc357e1617/href">https://medium.com/media/8a8bfda6a775c69a50c8a0bc357e1617/href</a></iframe><p>Or subscribeOn could be applied directly to the network request:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/725ff5a3c76c80c9023231f6b7e1f42a/href">https://medium.com/media/725ff5a3c76c80c9023231f6b7e1f42a/href</a></iframe><p>Either way, though, we must break our initial assumptions. Special cases could be made when working with Processor classes, but that is not a very satisfying approach.</p><p>The root issue here is assuming a single subscribeOn call at the end of the call chain was ever the appropriate way to supply threading for the whole call chain. Not only does the behavior of Processor classes make this impossible to use consistently, but it also ignores the fact that different parts of a call chain might be best to run using different kinds of Scheduler classes and that each function knows best which Scheduler it requires.</p><p><strong>It would seem, then, that a safer, more consistent pattern is to allow each function returning an RxJava type to apply its own threading and only expect the final consumer to be concerned with changing the downstream threading.</strong> Many RxJava users always knew this, but the difference could feel like a matter of choice or opinion. The behavior of Processor classes, however, makes the answer clear. In fact, this is exactly what Retrofit now does with its RxJava 3 adapter: by default, all network requests now run on a background thread unless specified otherwise.</p><h3>The Future</h3><p>It is likely that many RxJava projects have encountered unexpected behavior due to this subtle fact about Processor classes. The confusion here really stems in large part from the freedom with how the subscribeOn and observeOn operators can be used and how they actually work: they can be placed anywhere in a call chain, or not at all; rather than one strict pattern for their usage, several appear to be allowed; subscribeOn applies threading to all upstream operators, except when it doesn’t.</p><p>While freedom can be very powerful, sometimes in programming opinionated frameworks and forced behavior can ultimately lead to less mistakes and more coherent code. Fortunately in this regard, the Android community is moving away from RxJava and toward <strong>Kotlin Coroutines</strong>. There are two key differences that avoid surprise threading issues like the one we have been discussing in RxJava:</p><ul><li>Consumers of suspending functions or Flow instances are required to supply a CoroutineScope in order make the calls and receive results. Among other things, these scopes determine the Dispatcher used to define the threading behavior for any code downstream of the call in question and would be the equivalent of enforcing that observeOn is <strong>always called at the beginning</strong> of an RxJava call chain after the initial call.</li><li>There is a very clear pattern in the coroutines community (and pushed by the developers of coroutines themselves) that all suspending functions and Flow instances should apply their own threading and should therefore be safe to be called from any other coroutine.</li></ul><p>I go into detail on each of these points in a <a href="https://medium.com/livefront/coroutine-misconceptions-whose-context-is-it-anyway-320c0b7adcc7">previous article on coroutine threading behavior</a>.</p><p>Much like Kotlin has far overtaken Java, coroutines are undoubtedly the future for handling asynchronous work in Android. We must acknowledge, though, that as there are still many legacy projects that use Java, there will be many projects that continue to use RxJava. For these, it is important to be aware of the subtle threading issues discussed in this article and to also be mindful of adopting patterns that better match the threading behavior of Android’s future.</p><p><em>Brian works at Livefront, where threading is half the battle.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ad0579e55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/the-rxjava-threading-mistake-you-are-probably-making-58ad0579e55">The RxJava Threading Mistake You Are Probably Making</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutine Misconceptions: Whose Context Is It Anyway?]]></title>
            <link>https://medium.com/livefront/coroutine-misconceptions-whose-context-is-it-anyway-320c0b7adcc7?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/320c0b7adcc7</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Fri, 07 May 2021 19:44:51 GMT</pubDate>
            <atom:updated>2021-05-13T19:03:38.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>I know you like RxJava, but…</h4><p><strong><em>TL;DR</em></strong><em>: You should never need a call like </em><em>withContext(...) { suspendingFunction() }.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFMwyad5gATtxh4rQ4ainw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/tZIrJ3CgK_Y">John Anvik</a>.</figcaption></figure><p>Consider the following all-too-familiar task on Android: you must make a network request and update the UI with the resulting data. RxJava veterans will write the following without hesitation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2678129080c90124f52d007db38ccda8/href">https://medium.com/media/2678129080c90124f52d007db38ccda8/href</a></iframe><p>(I have assumed for simplicity that both a success and an error will be wrapped in the same object and emitted in the main channel.) Note the subscribeOn operator that places the upstream call on a background I/O thread and the observeOn operator that places the downstream updateUiWithResult call on the main thread. So common is this combination that most RxJava users writing in Kotlin are likely to have their own helper extension to apply both simultaneously:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0edda958b6f27b0cd77ac6834756d0c5/href">https://medium.com/media/0edda958b6f27b0cd77ac6834756d0c5/href</a></iframe><p>The question I am here to discuss, however, is what is the <em>best</em> way to represent such a call chain using Kotlin coroutines? It is not difficult to come across examples like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/481d9012fa83d116114c1602368db7d7/href">https://medium.com/media/481d9012fa83d116114c1602368db7d7/href</a></iframe><p>or</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4af2021cb56f0f9912f5a016ae507ab/href">https://medium.com/media/d4af2021cb56f0f9912f5a016ae507ab/href</a></iframe><p>or even</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a06ee1d4e2ee4b345133ce036471ebf/href">https://medium.com/media/8a06ee1d4e2ee4b345133ce036471ebf/href</a></iframe><p>These all compile and function correctly but I’d argue they should be treated as incorrect (or, at the very least, non-idiomatic and unnecessarily redundant). These all stem from the thinking that it is the <em>caller’s</em> responsibility to supply background threading to background operations and I contend that this is RxJava-style thinking that should not carry over to coroutines…and I’m not the only one.</p><h3>The Right Way</h3><p>So what does it look like if it is <em>not</em> the caller’s responsibility to supply threading? Consider the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbfdb17dc40e24edfb64cc223fd692f3/href">https://medium.com/media/cbfdb17dc40e24edfb64cc223fd692f3/href</a></iframe><p>There are two very important things to note here:</p><ul><li>viewModelScope (and the equivalents in an Activity or Fragment such as lifecycleScope) uses Dispatchers.Main by default.</li><li>getNetworkResult has not had any manual threading applied by the caller here using something like withContext(Dispatchers.IO).</li></ul><p>This first point means that any function calls (suspending or otherwise) that must be run on the main thread can be done so without any additional handling within this scope. Also, because you always need a CoroutineScope to call a suspending function in the first place, the question of “downstream threading” is naturally already answered before you even write the suspending calls themselves.</p><p>The latter point here is really the key, though. For this to be a safe call that does not result in a NetworkOnMainThreadException or otherwise block the main thread, we must assume that getNetworkResult now has threading “pre-applied” in a sense. This may go against the instincts of many RxJava users, but it is, in fact, the desired goal of both <strong>JetBrains</strong> (who develops Kotlin and coroutines) and <strong>Google</strong> (who continues to take a Kotlin-first and seemingly coroutines-first approach to new Android features).</p><h4>What JetBrains Says</h4><p>First, consider Roman Elizarov’s <a href="https://elizarov.medium.com/blocking-threads-suspending-coroutines-d33e11bf4761">article on the relationship between blocking calls and coroutines</a>. He makes very clear that the Kotlin community should adhere to a pattern in which <strong>“suspending functions do not block the caller thread”</strong>.</p><p>When writing a suspending function to wrap a blocking call, simply applying the suspend keyword does nothing to create a well-behaved suspending function and the Intellij IDE / Android Studio will even warn you about this. (I’d even go so far as to say it should be made a compilation <em>error</em> rather than a mere <em>warning</em>). It is the explicit application of withContext that imbues the function with the correct behavior:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2edb7b43123734a0cf904ee4288bfa27/href">https://medium.com/media/2edb7b43123734a0cf904ee4288bfa27/href</a></iframe><p>Failure to do so simply results in a function that must be called within a coroutine scope but still acts like a normal blocking call inside it. If we were being generous, this could be considered a “hint” that the call is blocking. However, because the most common coroutine scopes that an Android developer will deal with are ones that still run on the main thread (like viewModelScope), in a way this is just pushing the same problem to a different place and requiring more machinery to deal with it. With the correct Dispatcher already applied within the function body, this new function can be called safely from any coroutine scope and work correctly. This also means that you should never have to write something like withContext(...) { suspendingFunction() }.</p><h4>What Google Says</h4><p>This brings us to the general idea of <a href="https://developer.android.com/kotlin/coroutines/coroutines-best-practices#main-safe">“main-safety”</a>. This is Google’s way of labeling suspending functions that can be called from a coroutine scope that uses Dispatchers.Main without any additional handling:</p><blockquote>Suspend functions should be main-safe, meaning they’re safe to call from the main thread. If a class is doing long-running blocking operations in a coroutine, it’s in charge of moving the execution off the main thread using withContext. This applies to all classes in your app, regardless of the part of the architecture the class is in.</blockquote><p>This is really just an Android-specific way of stating Roman Elizarov’s key point about properly constructing suspending calls.</p><h4><strong>Third-Party Libraries?</strong></h4><p>And what about third-party libraries that feature suspending function calls? Any common, well-maintained library used by the Android community (such as <a href="https://github.com/square/retrofit">Retrofit</a>) is going to adhere to these same principles as well. In fact, while it was always an option to have threading pre-applied to RxJava types supplied by Retrofit, this is the <em>only</em> way you will receive a suspending function from it. This will typically mean that the only code where you really need to worry about making suspending functions “main-safe” is <em>your own</em>.</p><p>This really all comes down to a question of <em>responsibility:</em> who’s in charge of supplying background threading to calls that require them? Is it the <em>consumer</em> of the method or the <em>writer</em> of the method? Coming from RxJava — where it was more common to leave it to the consumer — it can be easy to try and carry over that style of thinking to coroutines. (I know that this is certainly how I approached it when first learning about them myself). As a community, though, we have a chance to establish a better, stronger pattern this time around. We have a chance to stop thinking about <em>placing</em> a suspend function on a background thread and start demanding that they already <em>be</em> on whatever thread they require. We have a chance to speak with one voice and say…</p><p><em>This is the way.</em></p><p><em>Brian works at </em><a href="https://livefront.com/"><em>Livefront</em></a><em>, where he *may* have been advocating for a suboptimal RxJava threading pattern this whole time…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=320c0b7adcc7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/coroutine-misconceptions-whose-context-is-it-anyway-320c0b7adcc7">Coroutine Misconceptions: Whose Context Is It Anyway?</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suspending Lambdas in Kotlin]]></title>
            <link>https://medium.com/livefront/suspending-lambdas-in-kotlin-7319d2d7092a?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/7319d2d7092a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Wed, 11 Nov 2020 19:46:56 GMT</pubDate>
            <atom:updated>2020-11-11T20:08:27.074Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>TL;DR</em></strong><em>: Use </em><em>suspend { ... } to create a suspending lambda. That is all.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TcgLKS_unBU18G0DB1pT7g.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/photo/landscape-man-people-woman-3947403/">Rodolfo Clix</a></figcaption></figure><p>When first working with Kotlin coroutines you will quickly come across the suspend keyword as a means of marking a function as a <em>“suspending function”</em>. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31094ccc619f46558be0f5267fa1bce8/href">https://medium.com/media/31094ccc619f46558be0f5267fa1bce8/href</a></iframe><p>There are times, however, where you will run into more exotic usages. Consider the following preview function from the coroutines core library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b1ea3031c7aba9f37b59ea7009a71d8/href">https://medium.com/media/1b1ea3031c7aba9f37b59ea7009a71d8/href</a></iframe><p>This extension allows for a typical suspending function to be converted to a Flow. In this case, the suspend keyword is being used to describe a functional type which is suspending:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb353cbb9313863ed8b6ee9d6563d17/href">https://medium.com/media/6bb353cbb9313863ed8b6ee9d6563d17/href</a></iframe><p>This intuitively makes some sense: just as there is a way to define non-suspending functional types like () -&gt; T, there should also be a way to define suspending ones. The example given in the documentation for the function above provides one way to get a reference to a function of such a type. Given a no-argument suspending function like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/352fda41267ae1b18cac263f7745daab/href">https://medium.com/media/352fda41267ae1b18cac263f7745daab/href</a></iframe><p>A function of type suspend () -&gt; R can then be returned via the function reference ::remoteCall. This is simply the suspending equivalent to the non-suspending case. For example, given</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a18b9e96d4b0874815e9608f21facbc/href">https://medium.com/media/8a18b9e96d4b0874815e9608f21facbc/href</a></iframe><p>the function reference ::nonSuspendingCall will be of type () -&gt; R.</p><p>The question, however, becomes: how does one define such a functional type using a <em>lambda</em>? Consider the following suspending function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a491054649a7178ecfc98e08cc73b24/href">https://medium.com/media/5a491054649a7178ecfc98e08cc73b24/href</a></iframe><p>The function reference ::downloadFile has a type of suspend (String) -&gt; File and would not, for example, be suitable for use with the asFlow helper. You may be tempted to try and use the helper method by defining a lambda as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/948d27ae8bc31527e5402abb20b83d11/href">https://medium.com/media/948d27ae8bc31527e5402abb20b83d11/href</a></iframe><p>This does not compile, though, when called outside a suspending function and will result in the error message:</p><blockquote>Suspend function ‘downloadFile’ should be called only from a coroutine or another suspend function</blockquote><p>You may have guessed that verbosity can save the day here if we explicitly denote the lambda as having the suspending type we are looking for:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/853e68490390e1153d669858e1ad1502/href">https://medium.com/media/853e68490390e1153d669858e1ad1502/href</a></iframe><p>This does, in fact, work but it is also not entirely satisfying: as Kotlin developers we are spoiled by type inference and feel entitled that it should exist for this case as well. Luckily there is a way to give us the result we crave with another very interesting usage of the suspend keyword in which it is prepended to the lambda definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f0a40693667054160ecdc785a94727d/href">https://medium.com/media/0f0a40693667054160ecdc785a94727d/href</a></iframe><p>The syntax suspend { … } results in a “suspending lambda” and produces a function of type suspend () -&gt; T, which is exactly what we are looking for. With this syntax, suspending lambdas can take their place alongside their non-suspending siblings as another valuable tool in our coroutines (and Kotlin) toolbox.</p><p><em>Brian writes suspending………………lambdas at </em><a href="https://livefront.com/"><em>Livefront</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7319d2d7092a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/suspending-lambdas-in-kotlin-7319d2d7092a">Suspending Lambdas in Kotlin</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TransactionTooLargeException and a Bridge to Safety — Part 2]]></title>
            <link>https://medium.com/livefront/transactiontoolargeexception-and-a-bridge-to-safety-part-2-36c58809d2db?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c58809d2db</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 22:39:05 GMT</pubDate>
            <atom:updated>2019-12-18T22:42:32.493Z</atom:updated>
            <content:encoded><![CDATA[<h3>TransactionTooLargeException and a Bridge to Safety — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pSk6bNgMWE3_mEnO" /><figcaption>Photo by<a href="https://www.pexels.com/photo/aerial-view-of-bridge-1211856/"> Immortal shots</a></figcaption></figure><p>In the<a href="https://medium.com/livefront/transactiontoolargeexception-and-a-bridge-to-safety-part-1-c3736644e26"> first article of this series</a>, I discussed what TransactionTooLargeException is, when and why it happens, and how the <a href="https://github.com/livefront/bridge">Bridge</a> library can be used to avoid the problem. If you are not yet familiar with how to use Bridge you should definitely check out that article before continuing. What I’d like to do now is to take a peek inside the library itself and focus on a few tricks used to make it all work. First, though, we have a bit of bookkeeping to discuss.</p><p>A quick look at the documentation will show that all the interactions with Bridge take the form of static method calls: Bridge.saveInstanceState, Bridge.restoreInstanceState, etc. However, there is very little actual code in the Bridge class itself. Apart from checks to make sure the initialize method has been called, each static method simply calls through to a static instance of a different class, BridgeDelegate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c00d302c604c724cc98f921a4b6d8e/href">https://medium.com/media/a7c00d302c604c724cc98f921a4b6d8e/href</a></iframe><p>BridgeDelegate is where all the action actually takes places and this will be the focus of the discussion below. It is also important to emphasize that I’ll be presenting a somewhat simplified version of that code in order to focus on the core functionality.</p><h3>A Look Inside</h3><p>In order to avoid a TransactionTooLargeException when sending too much data across processes after onSaveInstanceState, Bridge must do a few key things:</p><ul><li>Bypass sending the data to system_process and store it “locally” (i.e. solely within reach of your app’s own process).</li><li>Save the data both in memory (for quick use across configuration changes) and to disk (for use after process death and recreation).</li><li>Effectively link a given instance of a class to its own stored data (even after process death and restoration).</li></ul><p>Let’s take a high-level look at the two main methods in BridgeDelegate involved in actually saving and restoring data and then discuss all the key points below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e831054fd583fda6e85bfc4420fdd66/href">https://medium.com/media/1e831054fd583fda6e85bfc4420fdd66/href</a></iframe><h4>Bridge generates keys that are stored in the usual Bundle</h4><p>The first action taken when attempting to save data is to create a unique key that can be used to find that data later. This is done using a UUID returned from a call to getOrGenerateUuid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c92b29251a1eee9b467ada783a1a9419/href">https://medium.com/media/c92b29251a1eee9b467ada783a1a9419/href</a></iframe><p>You’ll note that once we have generated a UUID, we will associate that key with the Object itself in a Map; this allows us to avoid generating multiple keys for the same object, which prevents the same data from being unnecessarily written to disk multiple times later on. It is also very important that the Map used is a WeakHashMap: because a single instance of BridgeDelegate is held as a static variable in the Bridge class, holding strong references to the targets themselves would result in memory leaks (and of Activity and Fragment instances no less!).</p><p>Once we have a UUID for the target, that value is then stored in the original Bundle sent in with the target:</p><pre>state.putString(getKeyForUuid(target), uuid);</pre><p>This UUID is<strong> <em>the only piece of data</em> </strong>Bridge will store in the original Bundle for a given target and this fact is what prevents TransactionTooException from ever occurring: rather than placing an arbitrary amount of data in a Bundle we are now only storing a single String. In this way, we leverage Android’s existing saved state framework to hold the unique locator we will need for “locally” managing the actual saved state ourselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MofhNxBLQQcNIyGFhi0mg.png" /><figcaption>Without Bridge, generic Bundle data will be sent directly to system_process via IPC, where it will be subject to a potential TransactionTooLargeException.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Fh81wHYMdiy001cnUS8Vw.png" /><figcaption>With Bridge, only a UUID will be sent to system_process for a given target. The generic Bundle data will be intercepted and stored safely within reach of an application’s own process.</figcaption></figure><p>Before we move on to the discussion of where the <em>actual</em> saved data goes, let’s mention one final point. Note from above that the key used is based on the name of the target class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08e5dd63c227622b293e10696ce3a1f6/href">https://medium.com/media/08e5dd63c227622b293e10696ce3a1f6/href</a></iframe><p>This allows Bridge to manage the state of other objects (like presenters or viewmodels) in addition to Activity and Fragment instances if necessary. Multiple keys can then be safely tracked in the same Bundle of a given Activity / Fragment (assuming, of course, that an attempt is not made to save the state of different instances of the same class in the same Bundle, which would not typically be done anyway with or without Bridge).</p><p>Now let’s take a look at where the actual data goes and how the UUID is used to retrieve it.</p><h4>Bridge places the actual data in a completely separate Bundle</h4><p>Next, using the SavedStateHandler instance passed to the Bridge.initialize call, Bridge populates a completely new Bundle with the data a caller is actually interested in saving:</p><pre>Bundle bundle = new Bundle(); mSavedStateHandler.saveInstanceState(target, bundle);</pre><p>Recall that this SavedStateHandler is just an abstraction around libraries like <a href="https://github.com/frankiesardo/icepick">Icepick</a>, <a href="https://github.com/evernote/android-state">StateSaver</a>, etc. that pull data from the annotated fields / properties of the target object and place them in the supplied Bundle. The usage here follows their typical behavior, but rather than passing the original Bundle supplied by the OS in onSaveInstanceState we have supplied our own.</p><h4>Bridge saves these new Bundles to memory</h4><p>Now that we have a Bundle of our own and a UUID we can use to uniquely match it to the source object, we can begin storing that Bundle for later reuse.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71599c37a1e94bea29716401a254331a/href">https://medium.com/media/71599c37a1e94bea29716401a254331a/href</a></iframe><p>The first thing we’ll do is save it to memory. This is the easy part: we’ll simply associate each UUID and Bundle pair in a Map:</p><pre>private Map&lt;String, Bundle&gt; mUuidBundleMap = new HashMap&lt;&gt;(); </pre><p>Now, before discussing how we further persist this data to disk, let’s review the steps we can use to pull this saved data from memory and restore it to our target object. When we call restoreInstanceState, retrieval of this in-memory Bundle is simple:</p><ul><li>As a complement to the getOrGenerateUuid method discussed above for getting a new or cached UUID for a given target, we can call getSavedUuid to pull the UUID out of the external, OS-provided Bundle (or directly from the in-memory map where available).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f7f9c93d93413e96678f5034d770a34/href">https://medium.com/media/0f7f9c93d93413e96678f5034d770a34/href</a></iframe><ul><li>If we find an associated UUID, we then call getSavedBundle to pull the matching Bundle from the in-memory mUuidBundleMap, only falling back to the disk-persisted data if it is not already present here.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae39fb2ad6119a394610fb6c5050d806/href">https://medium.com/media/ae39fb2ad6119a394610fb6c5050d806/href</a></iframe><ul><li>Finally, if we successfully retrieve a Bundle we can restore the saved state in question using our SaveStateHandler once again:</li></ul><pre>mSavedStateHandler.restoreInstanceState(target, bundle);</pre><p>We have now saved and restored a target’s data without ever having to send it to system_process for safe keeping! Let’s now look at the last few tricks used to do the final, key piece of the puzzle: persisting the data to disk.</p><h4>Bridge can persist generic Bundles to disk</h4><p>When it comes to persisting data to disk in Java, the primary means of achieving this generically is via the Serializable interface. A quick look at the Bundle class — the form in which all our data is now stored — reveals, however, that <strong>it does not implement Serializable</strong>. That is pretty bad news for a quick, easy solution. A Bundle <em>is</em> Parcelable, but that is a format meant for transferring data across processes via a Parcel, not for writing it to disk. A Bundle also does not exclusively contain simple data types that are <em>themselves </em>Serializable or otherwise easily-persistable: in addition to simple types like String and Float there can also be Parcelable data, IBinder references, and even other Bundle instances!</p><p>Fortunately, with a few good assumptions and a lucky bit of documentation, we can in fact find a way to make this work. Let’s go back to the earlier statement that the Bundle class implements Parcelable. Is there anything there that can help us? Well the Parcelable interface itself really only allows us to do two things: read from and write to Parcel objects.</p><p>So what about the Parcel class? This is where we start to find our way forward: there is a method called Parcel.marshall() that returns the content of the Parcel as a byte array (and a corresponding Parcel.unmarshall(byte[], int, int) to read those same bytes back to a Parcel). This is now beginning to look very much like Serializable: generic objects go in and bytes come out. If we can use this to get bytes from a generic Bundle we should be able to write that Bundle to disk however we choose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8145qN8TXg1un9ILcWDRg.png" /><figcaption>Under certain conditions, a Bundle may be safely written out as bytes and then back again.</figcaption></figure><p>Before proceeding, let’s first take a look at the <a href="https://developer.android.com/reference/android/os/Parcel.html#marshall()">documentation</a> for Parcel.marshal():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9acac82f22441425fa9bab1dd93959ef/href">https://medium.com/media/9acac82f22441425fa9bab1dd93959ef/href</a></iframe><p>OK, so that first sentence is pretty bad news:</p><blockquote>The data you retrieve here <strong>must not </strong>be placed in any kind of persistent storage (on local disk, across a network, etc).</blockquote><p>That would seem to put an end to this particular strategy of attempting to save a generic Bundle to disk. What ends up saving us, though, is the last sentence:</p><blockquote>The Parcel marshalled representation is highly optimized for local IPC, and as such does not attempt to maintain compatibility with data created in different versions of the platform.</blockquote><p>This is the “lucky bit of documentation” I previously mentioned. They could have just left it at “don’t do this,” but this additional explanation for <em>why</em> you shouldn’t attempt to persist these bytes to disk is <em>just</em> enough information to allow us to brazenly disregard the warning and do just that. The reason we can do so brings us to our assumptions:</p><ul><li>Even though Bridge will persist these bytes to disk (in direct violation of the warning) they will only ever be used in process-death-and-restoration scenarios. This means that any fresh launch of an app using Bridge will not read this data from disk, let alone pass it to Parcel.unmarshall(byte[], int, int). In particular, updates to the Android version of a user’s device will require a device restart, which means that the next time an app using Bridge is launched, there will be no associated saved state andBridge will therefore not attempt to read this data in this scenario either. So even though we are persisting the data, if we can assume the documentation’s explanation for the warning is both <em>accurate</em> and <em>complete</em> then we know we will not encounter any issues because we will never try to read that data back to an incompatibleParcel implementation.</li><li>The next assumption brings us to something the Parcel.marshall() documentation leaves out: that this method will actually crash if it contains references to objects that can not be written out as bytes. This includes obscure things like <a href="https://developer.android.com/reference/android/os/IBinder">IBinder</a> references, some rendering-specific things like <a href="https://developer.android.com/reference/android/view/Surface">Surface</a>, and some more common but very-highly optimized classes like <a href="https://developer.android.com/reference/android/graphics/Bitmap">Bitmap</a> (which delegate their writeToParcel calls to special native code). Bridge makes the assumption that these kinds of classes are simply not the kind of data that would be <em>manually</em> placed in aBundle in onSaveInstanceState (although Bridge does actually make an exception for Bitmap by “un-optimizing” it when writing to a Bundle because hey, you never know).</li></ul><p>With these two key assumptions, we can take our generic Bundle data, write it to disk, and then read it back later if required for process-death-and-restoration scenarios.</p><p>Let’s now take a quick look at what that looks like in our code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/839bc68351ae77a58091dd8df43bd09e/href">https://medium.com/media/839bc68351ae77a58091dd8df43bd09e/href</a></iframe><p>After getting our byte[] from the Parcel, we Base64 encode them as a String. This allows for quick and easy storage in a private SharedPreferences instance. Reading the data back is simply the inverse process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6504aa8dfbc79f5963a2055584d54394/href">https://medium.com/media/6504aa8dfbc79f5963a2055584d54394/href</a></iframe><p>We’ve gone from Bundle to disk and back again!</p><h4>Bridge leverages SharedPreferences</h4><p>One final word on the use of SharedPreferences: one usually expects SharedPreferences to be used for <em>small</em> amounts of data, not entire objects written to bytes and converted to a String. This is typically very important due to the synchronous nature of accessing data stored via SharedPreferences. It is worth noting, however, that a given SharedPreferences is really just a fancy wrapper around an XML file containing simple key-value pairs and that this wrapper has a number of nice properties for our particular use case:</p><ul><li>SharedPreferences only ever reads its disk content a single time: as soon as a particular instance is retrieved it loads its contents on a background thread and places it into a Map in memory. Calls to retrieve data from SharedPreferences only block if the data is attempted to be accessed while this background loading is underway; otherwise the data can be accessed immediately from the Map. If Bridge.initialize is called as one of the very first steps in a custom Application.onCreate, it is then possible that the stored data is already in memory by the time it is attempted to be retrieved in the first Activity of an application. And if there is still some amount of time the application needs to block while the SharedPreferences is loading, this takes place entirely at the startup of the application where small delays are already expected (rather than when navigating between screens, which could otherwise be jarring).</li><li>Different SharedPreferences instances point to different files, which allows all the Bridge data to be completely isolated from an application-specific data developers may store in other SharedPreferences instances.</li><li>SharedPreferences completely abstracts file handling, which allows the Bridge library to focus on the content it is trying to store and less on the details of the disk implementation itself.</li><li>When using SharedPreferences.Editor.apply(), changes can be easily written to disk on a background thread while also guaranteeing that an application won’t move to its next lifecycle state before this process is complete. This is very useful for Bridge, which must ensure that saved state data is completely written to disk before the application is fully in the “stopped” state when going into the background. Failure to do so might result in the application being killed before all the necessary data has been written to disk.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPU4kxC5kQQnFM2qVgLWJg.png" /><figcaption>The complete process from Bundle to SharedPreferences involves Base64 encoding the bytes coming from Parcel.marshall.</figcaption></figure><h3><strong>Final Thoughts</strong></h3><p>We’ve now reviewed the primary functionality of Bridge: saving and restoring arbitrary Bundle data without triggering TransactionTooLargeException. While TransactionTooLargeException may be a seemingly small and isolated problem, I hope to have impressed upon you that it requires more than just a little trickery and technical machinery to beat it.</p><p><em>Brian works at </em><a href="https://livefront.com/"><em>Livefront</em></a><em>, where it’s Bundles all the way down…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c58809d2db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/transactiontoolargeexception-and-a-bridge-to-safety-part-2-36c58809d2db">TransactionTooLargeException and a Bridge to Safety — Part 2</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TransactionTooLargeException and a Bridge to Safety — Part 1]]></title>
            <link>https://medium.com/livefront/transactiontoolargeexception-and-a-bridge-to-safety-part-1-c3736644e26?source=rss-2f3d9e7b8db------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3736644e26</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Brian Yencho]]></dc:creator>
            <pubDate>Wed, 27 Feb 2019 20:52:36 GMT</pubDate>
            <atom:updated>2019-12-18T22:43:57.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>TransactionTooLargeException and a Bridge to Safety — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ev8Zp-h7lxE6tyEDuzzwug.jpeg" /><figcaption><em>Photo by </em><a href="http://picmamba.com/"><em>Zdeno Ceman</em></a></figcaption></figure><p><strong>TL;DR</strong> : Stop worrying about TransactionTooLargeException; use <a href="https://github.com/livefront/bridge">Bridge</a>.</p><p>I still remember when I first read the <a href="https://developer.android.com/about/versions/nougat/android-7.0-changes#other">release notes </a>for Android Nougat in the summer of 2016. Buried alongside mostly innocuous changes to things you probably wouldn’t care about was something that jumped out at me:</p><blockquote>Many platform APIs have now started checking for large payloads being sent across Binder transactions, and the system now rethrows TransactionTooLargeExceptions as RuntimeExceptions, instead of silently logging or suppressing them. One common example is storing too much data in Activity.onSaveInstanceState(), which causes ActivityThread.StopInfo to throw a RuntimeException when your app targets Android 7.0.</blockquote><p>I would guess that many people glossed over this one, too, and I might have as well if it weren’t for the fact that <strong><em>I’d seen this before</em></strong>. Long ago, I’d seen direct evidence of the OS “silently logging” this problem: I’d noticed some strange state saving behavior and there, buried in all the other logs of the app I was working on, was this singular, aggressively punctuated line:</p><pre>!!! FAILED BINDER TRANSACTION !!!</pre><p>And that was it.</p><p>After a little investigation, I understood that we were sending too much data in our saved state Bundles. The Bundle couldn’t be sent to the OS for safe keeping, so it was just getting dropped on the floor. For actual users experiencing this situation, the result would be that when the app process was killed while in the background and they returned to it, it would launch from a fresh state rather than a restored one. Less than ideal, sure. But, at the time, it seemed like a graceful enough fallback for the particular edge case I was seeing that “fixing” it became a problem for the backlog.</p><p>But then, <em>Nougat happened</em>. I suspected TransactionTooLargeException would sneak up on a lot of developers, and those suspicions were confirmed when I started seeing all the Stack Overflow questions and “bugs” filed with the Android Issue Tracker, like <a href="https://issuetracker.google.com/issues/37103380">“TransactionTooLargeException on pausing app”</a>. The message from Google, though, was clear:</p><blockquote>Status<br>Won’t Fix (Intended behavior)</blockquote><p>And that’s when I decided to do something about it.</p><h3>The Problem</h3><p>Before talking about our solution, let’s first go a little deeper into the actual problem. At its core, Android is just a customized version of Linux in which each application runs in its own separate process. This is true of the core functionality of the operating system itself, which runs in a process very creatively named <strong><em>system_process</em></strong>. In order for an application to function, it needs to communicate with <strong><em>system_process</em></strong> via a special form of inter-process communication (IPC) called <strong>“Binder IPC”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXudgMeij2yYxeiyO-TpTQ.png" /><figcaption>You application process communicates with the OS’s <strong>system_process</strong> via Binder transactions.</figcaption></figure><p>The Binder framework is a fascinating topic that gets to the core of how Android works (and has a history stretching back to Palm OS) but I’ll summarize a few relevant details here:</p><ul><li>Binder IPC allows communication to occur synchronously in each process via a “transact” method. These <strong><em>“Binder transactions” </em></strong>pass data between the processes via highly optimized data containers called <a href="https://developer.android.com/reference/android/os/Parcel"><strong><em>Parcel</em></strong></a>.</li><li>Several familiar Android objects like<strong> Intent</strong>, <strong>Bundle</strong>, and <strong>Parcelable </strong>are ultimately packaged in <strong>Parcel </strong>objects in order to communicate with <strong><em>system_process</em></strong>.</li><li>Creating / starting / stopping / pausing / resuming / etc. an Android Activity all involve making Binder transactions.</li><li><strong><em>Each app process has a 1 MB buffer for all Binder transactions.</em></strong></li></ul><p>That last key point is critical : if at any point one of the Parcels becomes so large that its corresponding transaction overflows the 1 MB buffer, we say that the <strong><em>transaction was too large</em></strong>. Hence we get the name, <strong><em>TransactionTooLargeException</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syULXah7rhw7fw3jC2fO4Q.png" /><figcaption>If a Binder transaction pushes the buffer past the 1 MB limit, a TransactionTooLargeException is triggered.</figcaption></figure><p>To make matters worse, because the 1 MB limit is on the *buffer* and not on an individual *transaction*, the transactions that actually push things over the limit are typically much smaller and more like ~0.5 MB. Unless you’re simply storing a few primitives here and there, that’s not a lot of data.</p><p>This brings us to one of the key places this can all go wrong in an app : onSaveInstanceState. An example implementation might look something like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9c02fab39ca83f0d619e37cbb3dff69/href">https://medium.com/media/c9c02fab39ca83f0d619e37cbb3dff69/href</a></iframe><p>This method is called in an Activity when it is in the process of being placed in the “stopped” state. When that happens, the OS needs to acquire all the relevant information for that Activity that it might need to later “restore” it, whether that’s after a configuration change or when the app’s process is killed while backgrounded and the user returns to it. The data collected in the Bundle passed to this method is then converted to a Parcel and sent directly to <strong><em>system_process </em></strong>via a Binder transaction. If the custom mData object is so large that the transaction fails, you’ll see something like the following error message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d41853524fb36093a50fbcb84bb757d/href">https://medium.com/media/7d41853524fb36093a50fbcb84bb757d/href</a></iframe><p>That’s the TransactionTooLargeException we want to solve.</p><h3>A Word of Caution</h3><p>Before continuing, let us first state the obvious : the best way to avoid TransactionTooLargeException is to avoid being in the position to trigger it in the first place. That means following the recommendations that have always been given by Google : <strong>just don’t put too much stuff in the saved state Bundle.</strong> For a “modern” description of Google’s recommended way of handling state saving and restoration, there’s a <a href="https://medium.com/androiddevelopers/viewmodels-persistence-onsaveinstancestate-restoring-ui-state-and-loaders-fc7cc4a6c090">great article by Lyla Fujiwara</a> called <strong>“ViewModels: Persistence, onSaveInstanceState(), Restoring UI State and Loaders” </strong>that discusses how to best use the onSaveInstanceState callback in conjunction with <strong>ViewModel</strong> and <strong>Room</strong> from the Android Architecture components. To summarize the key, general points:</p><ul><li>Just put simple data like identifiers in the onSaveInstanceState Bundle.</li><li>For state that you only need to save across configuration changes (like rotations), just save it in memory.</li><li>For any state you really want to have after the app is restored after process death, you should persist it to disk in some kind of database.</li></ul><p>These are all great ideas and should absolutely be followed, but there may be some cases where that it is not immediately possible or preferable: you may not have the time or budget for a large refactor; you might only have this problem in one isolated part of your app and under very unique conditions; maybe you just have an architectural pattern you really like that makes heavy use of the onSaveInstanceState method.</p><p>This is why we created <a href="https://github.com/livefront/bridge">Bridge</a>, a simple library for avoiding this problem with minimal code changes to an existing app. In addition to hinting at its role in helping transport data from one location to another, its name is also meant to imply that this might not be the <em>ultimate solution</em> to your problem, but just something that helps you get there. Buying time to stop and think can be a powerful thing.</p><h3>Bridge and How To Use It</h3><p>Let’s finally take a look at an example of using Bridge. First, here’s what an Activity might look like before using it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d55cb68915eb3c46d70eb00f230e82/href">https://medium.com/media/09d55cb68915eb3c46d70eb00f230e82/href</a></iframe><p>Here we are using the excellent <a href="https://github.com/frankiesardo/icepick">Icepick library</a> to manage the saved state of the custom Parcelable data class, DataModel, using an @State annotation. As previously described, it is the saving of this model that might become too large under certain conditions and trigger a TransactionTooLargeException.</p><p>Bridge is actually modeled after Icepick and its usage is meant to be as close to a drop-in replacement as possible. Simply replace the Icepick methods with the corresponding Bridge ones and optionally add a call to Bridge.clear() in onDestroy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcaad6d0a5c377a563520eacc470f471/href">https://medium.com/media/dcaad6d0a5c377a563520eacc470f471/href</a></iframe><p>As one final step, all you need to do is initialize the library in the Application.onCreate of you app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad0fe5c5af09f1a28d6466e109db267e/href">https://medium.com/media/ad0fe5c5af09f1a28d6466e109db267e/href</a></iframe><p>The SavedStateHandler allows you to choose the library (or custom code) that will actually do the grunt work of reading and restoring saved state for your objects while the Bridge library handles the storage of that data in a safe way.</p><p>Like Icepick, Bridge works best when combined with a base class for your Activities / Fragments / etc:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/534f8a9f058bb039cbdcbcd9d9fdbb53/href">https://medium.com/media/534f8a9f058bb039cbdcbcd9d9fdbb53/href</a></iframe><p>This allows your classes to safely save state without repeating the same boilerplate over and over:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6122e7b601336ce59f52a0c1d61ec399/href">https://medium.com/media/6122e7b601336ce59f52a0c1d61ec399/href</a></iframe><p>And that’s all it takes to to go from an app suffering from TransactionTooLargeException to one that doesn’t!</p><p>So now you’ve seen what TransactionTooLargeException is, why we built <a href="https://github.com/livefront/bridge"><strong>Bridge</strong></a> to avoid it, and how to use it. To see what Bridge is actually doing under-the-hood, check out <a href="https://medium.com/livefront/transactiontoolargeexception-and-a-bridge-to-safety-part-2-36c58809d2db">Part 2</a>.</p><p><em>Brian works at </em><a href="https://livefront.com/"><em>Livefront</em></a><em>, where TransactionTooLargeException is a thing of the past.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3736644e26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/livefront/transactiontoolargeexception-and-a-bridge-to-safety-part-1-c3736644e26">TransactionTooLargeException and a Bridge to Safety — Part 1</a> was originally published in <a href="https://medium.com/livefront">Livefront</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>