<?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 Damian Burke on Medium]]></title>
        <description><![CDATA[Stories by Damian Burke on Medium]]></description>
        <link>https://medium.com/@burkedamian?source=rss-19f55fe0f271------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D-4sENv_II5OPTca.</url>
            <title>Stories by Damian Burke on Medium</title>
            <link>https://medium.com/@burkedamian?source=rss-19f55fe0f271------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:09:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@burkedamian/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[Automating Code Reviews]]></title>
            <link>https://proandroiddev.com/automating-code-reviews-f586f2281a2e?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/f586f2281a2e</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 08:56:31 GMT</pubDate>
            <atom:updated>2020-09-16T19:54:43.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPb3sHHun3Ng1VfnKoIUBA.png" /></figure><p><strong>Building software is a complex task.</strong> Some software is built by a single person, but often times there are teams behind software. These teams can range from two people up to hundreds of people. Working with many people in the same code-base brings quite a few challenges. Tools like <em>git</em> help out with working in parallel by enabling us to version our code (i.e. see changes over time) or to easily spot changes suggested by team members. But the more people are working on the same code-base, the more changes are being suggested — and these changes need to be reviewed by someone.</p><p>To ensure a consistent code quality, <strong>code review</strong> is a core part of a software engineer’s day. There are multiple aspects when reviewing code — more visual ones like conforming to a commonly defined code style (formatting, indentation, braces, …) but also logical aspects like the correctness of the code, usage of architecture patterns, performance, and more. To reduce the workload that reviewing code puts on the team, <strong>we can automate parts of the code review process</strong>. In the following we will take a look at adding automation to our code reviews with a focus on code style and static code analysis. The examples will be based on <strong>Kotlin</strong> (in an <strong>Android</strong> app) — but they are applicable to other projects as well, for example Swift, Dart or others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5JjMFChsuiSeTDaZIq7aQ.png" /></figure><p>Working in a team means that <strong>decisions are made as a team</strong>. These decisions can be related to workflows, software architecture or just about the commonly used code style. Some of these decisions can be incorporated into the daily workflow — for example into the IDE via .editorconfig for formatting, or a commonly shared code style file that can be imported into the IDE. Many other decisions can’t be included and instead must be documented somewhere to keep track of them. This allows existing team members as well as new joiners to understand what decisions have been made by the team, and to adjust to them.</p><p>Taking decisions and writing them down is only one part though — these decisions need to be followed. This requires the team to be aligned and work into the same direction. Everyone on the team needs to be aware of them and willing to follow them. <strong>It’s easy to forget</strong> about certain things as well, and code review is usually the place where people are reminded of these things.</p><p>With a growing team and a growing number of pull requests (or merge requests), time spent in code review also grows. There have been <strong>many pull requests with most of the comments regarding code style</strong> or certain things that have been decided and written down before — just because someone was not aware of them or forgot about it. <strong>This costs a lot of time</strong>: Reading the code, focusing on the code style, spotting issues, writing comments which then are addressed. Often times issues are duplicated, resulting in duplicated comments and review work.</p><p>Lets take a look at how this can be automated.</p><p>The tools we will be using are:</p><ul><li><a href="https://danger.systems/js/">DangerJS</a></li><li><a href="https://github.com/damian-burke/danger-plugin-lint-report">Danger Plugin: Lint Report</a></li></ul><p><strong>DangerJS</strong> is the backbone of the setup, it will be triggered for each pull request and run a couple of checks on the changes.</p><blockquote>Danger runs during your CI process, and gives teams the chance to automate common code review chores.</blockquote><p>By writing a JavaScript file we can write a simple script that accesses the pull request (and its meta-data) and executes checks.</p><p>An example — checking if a pull request modifies a changelog file (CHANGELOG.YML):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9a5c53ea1c763df1f7ab1077f3c3ddd/href">https://medium.com/media/c9a5c53ea1c763df1f7ab1077f3c3ddd/href</a></iframe><p>If the author didn’t add the changes to the changelog (or technically: if there was no modification of the changelog file in the pull request), a review comment will be posted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*6ykLpZtlq9uDN-bwGJ2Hiw.png" /><figcaption>Example review comment for missing changelog modification</figcaption></figure><p>This alone is a quite powerful tool that can reduce the amount of time required for code review. It can be extended to fit certain workflows — for example making sure that the software version is increased before a release or to post warnings if business critical parts of the code-base are being touched.</p><p><strong>DangerJS has full access to the checked out commit</strong> — both the source directories as well as the build output. This allows us to execute a couple of steps before triggering DangerJS in our pipeline, and to utilize the results.</p><p>Our goal is to automate parts of the code review process — especially the ones that are focused more on code style issues. So we will <strong>embed a linter and static code analysis into the pipeline</strong>.</p><p>Looking at a Kotlin code-base, the linter of our choice will be <a href="https://github.com/pinterest/ktlint"><strong>ktlint</strong></a>. For static code analysis we will be using <a href="https://github.com/detekt/detekt"><strong>detekt</strong></a>.</p><p><strong>ktlint will make sure that the formatting of our code stays consistent</strong> — we follow the same indentation rules, variable naming, braces and much more. This will ensure that different parts of the code-base can be read in the same way and thus it’s easier to switch between them.</p><p><strong>detekt will keep the code complexity low. </strong>It contains rules about concurrency usages, performance optimizations and general code structure.</p><p>To add both ktlint and detekt to our pipeline, and to enable DangerJS to use their reports, we need to enable XML reports. The DangerJS plugin is able to read checkstyle-formatted reports — meaning it is not limited to ktlint and detekt, but it can also read <strong>SwiftLint </strong>or other linters’ reports.</p><p>This example will be using GitHub actions to execute the CI pipeline — since DangerJS will be working closely with the pull requests, GitHub actions bring the benefit of supplying a GitHub actor and token out of the box.</p><p>The workflow for DangerJS on GitHub Actions looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde8feeb318da9308e7153b5b74570cc/href">https://medium.com/media/bde8feeb318da9308e7153b5b74570cc/href</a></iframe><p>This will install Danger and trigger it on pull requests. DangerJS will look for the configuration file (Dangerfile) and execute it. This could be used with the changelog modification script posted above.</p><p>The next step is to add the lint report plugin. Since it’s a different package, we’ll need to install it in the workflow as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95662346952f2158d97ca4d4a3c5518d/href">https://medium.com/media/95662346952f2158d97ca4d4a3c5518d/href</a></iframe><p>Now we can adjust our DangerJS configuration (Dangerfile) and include our ktlint reports:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c404b4b7e0a6455999b40cb66c2c5f35/href">https://medium.com/media/c404b4b7e0a6455999b40cb66c2c5f35/href</a></iframe><p>The last thing for us to do is to add ktlint to our GitHub Action. Since the lint reports are not committed, and thus not added to the repository, the file search for **/reports/ktlint/*.xml would not find any reports — and subsequently not be triggered.</p><p>The updated workflow file with a step to execute ktlint before Danger:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b7bdc6d6c94899e383def28fa57fa9/href">https://medium.com/media/61b7bdc6d6c94899e383def28fa57fa9/href</a></iframe><p>Opening a pull request will now trigger ktlint and then DangerJS — which will use the plugin we installed to scan for ktlint reports, parse them, and post <strong>issues that were created in this pull request</strong> as review comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVwUicYT2d1t31Gw4tduMw.png" /></figure><p>The full Android setup, with <strong>ktlint</strong>, <strong>detekt</strong> and <strong>Android Lint </strong>would have a GitHub workflow triggering each of them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbcfbf8b0fd22269ac36059edc6a0244/href">https://medium.com/media/bbcfbf8b0fd22269ac36059edc6a0244/href</a></iframe><p>With the following Dangerfile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c120e634305bd6dcffccbd5cf2893a/href">https://medium.com/media/e9c120e634305bd6dcffccbd5cf2893a/href</a></iframe><p><strong>The result is that the team members no longer have to keep an eye out for mundane things like code style during the code reviews.</strong> This will save a lot of time long-term and ensure that the team’s own best practices are being followed.</p><p>To <strong>continuously improve this setup</strong> the rule-sets of each of these steps can be adjusted to perfectly fit the team’s desires. The next step would be to write custom rules (for each of these) to automate not just the code style decisions made by the team, but also rules about for example concurrency (in Kotlin this could be rules about Coroutine scope or context usages) or other more complex topics.</p><p><a href="https://github.com/damian-burke">damian-burke - Overview</a></p><p><a href="https://twitter.com/damian2048">https://twitter.com/damian2048</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f586f2281a2e" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/automating-code-reviews-f586f2281a2e">Automating Code Reviews</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inverting the Dependency — Independent Features in Android Applications]]></title>
            <link>https://proandroiddev.com/inverting-the-dependency-independent-features-in-android-applications-15453f3d7940?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/15453f3d7940</guid>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Mon, 08 Jul 2019 17:41:26 GMT</pubDate>
            <atom:updated>2019-07-09T08:04:19.539Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inverting the Dependency — Independent Features in Android Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*kAl9LWZZLo_xyiYi.jpg" /></figure><p>Working in a cross-functional team on an Android application imposes certain requirements on the code-base. The less structured the codebase is, the more conflicts will surface during the development cycles. Resolving these conflicts takes a lot of time, which could be utilized in a more productive way. Let’s take a look at how modularization and the independence of feature modules can assist cross-functional teams in working on the same code-base.</p><p>Looking at the dependency graph of most Android applications, we quickly notice that in most applications there is an app module on the top that knows about all feature modules. The feature modules have dependencies on shared common modules or on a shared core layer. This results in a fairly static architectural shape that makes it easy to introduce hard dependencies between features: A monolith.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*r_Sn1PUkkTQpwNSvOYvEdA.png" /></figure><p>It is perfectly fine to build monolithic applications and in some use-cases it is the obvious and preferred choice, but with growing teams and an increasing amount of features within applications, breaking the dependency chain makes it easier to understand parts of the code-base. This belongs in the same group as inheritance. It can make things easier and faster to develop, but if overused introduces code smells that will come back to haunt the developers at some time (if they are still in the company). Unexpected side-effects can be mitigated by ensuring there are proper test-suites in place covering the different layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Sbwzvrs__T0oSO18wa8TdQ.png" /></figure><p>With inter-feature dependencies, the graph turns from a once manageable pyramid into a messy knot of arrows. Depending on the navigation pattern used throughout the application, it becomes as simple as requiring to display a user interface element or a screen within a certain flow to introduce inter-feature dependencies. For more information regarding navigation patterns in modular applications, <a href="https://blog.usejournal.com/navigation-in-modular-applications-with-deep-linking-6a599c11e487">read this comparison of different approaches.</a></p><p>To avoid long-term problems with an intertwined dependency graph and to move away from a monolithic architecture, we are going to re-imagine features as satellites instead of pillars in our architecture. Features should be outside of our core application, in a place where they can be reached by other features and the core application, but also where it is easy to replace or even remove them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*RQ3SthLuyv6Labf4B3NZ9g.png" /></figure><p>The purpose of this architectural change is to make the base application independent of features. By removing the features from the base (app — common — core) we gain a couple of things:</p><p>Our base application is compilable and runnable with as few or as many of our feature modules as we wish. This means we can build a variant of our application that contains only one feature module to enable encapsulated testing or in a freemium business model we can build variants of the application that contain premium features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*vxdd2w_LextgzhMbuzTjRg.png" /></figure><p>The feature modules are reachable from within the application as well as other features without any hard (or compile-time) dependencies. This allows us to utilize hot loading — features can be added (or removed) seamlessly during runtime (plug and play).</p><p>To make full use of this feature-satellite approach, we also need to re-think the way we are accessing features in general. This refers to both accessing features from the base application as well as inter-feature communication. We have imposed a couple of constraints onto ourselves regarding the usage of features:</p><ul><li>Features may not be in the build variant</li><li>Features may be loaded during run-time</li><li>There can be different features implementing the same functionality</li><li>There can be multiple features implementing the same functionality</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*yAp5LQq5vjgFQI9nAlFHBg.png" /></figure><p>To understand how we can use feature satellites while respecting these constraints, we will create a couple of imaginary feature modules with different capabilities to show how to handle different use-cases.</p><p><strong>Scenario 1:</strong> The feature-satellite provides a service to manipulate data.</p><p><strong>Scenario 2:</strong> The feature-satellite provides us with certain Views or other UI elements.</p><p><strong>Scenario 3:</strong> The feature-satellite provides a complex UI flow with multiple screens.</p><p>There are multiple ways of achieving our goals. Both Java and the Android SDK offer us tools to achieve our goals, so we will first take a look at how we can express these requirements in code. In each of these scenarios the feature is a service providing a certain action or implementing a certain capability. In the coming examples we will look at this from a Capability point of view, to keep the naming consistent.</p><p><strong>Scenario 1:</strong> The feature’s capability is to manipulate data.</p><p><strong>Scenario 2: </strong>The feature’s capability is to create Views or other UI elements.</p><p><strong>Scenario 3:</strong> The feature’s capability is to guide the user through a complex UI flow.</p><p>To express this in a programmatic way, we will create a base interface for any of these capabilities:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a924bc2ded0abca60b8915a38465ef61/href">https://medium.com/media/a924bc2ded0abca60b8915a38465ef61/href</a></iframe><p>To make the examples more specific, we will narrow down our scenarios a bit:</p><p><strong>Scenario 1: </strong>The feature can remove the saturation of a given Bitmap.</p><p>For this scenario we simply create a new capability interface that expresses this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/220883bf18c0adf36770e9bdd4a010bc/href">https://medium.com/media/220883bf18c0adf36770e9bdd4a010bc/href</a></iframe><p>The feature-satellite would then contain an implementation of this capability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69ff1f0cabb843f5a4c7bc90c08ad3a1/href">https://medium.com/media/69ff1f0cabb843f5a4c7bc90c08ad3a1/href</a></iframe><p><strong>Scenario 2:</strong> The feature can create a button with a text displaying the headline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f5f2760b054b0213a92cec9ca3d7892/href">https://medium.com/media/4f5f2760b054b0213a92cec9ca3d7892/href</a></iframe><p>With an implementation of the interface that simply inflates an XML contained within the feature module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fc5172199ad0fef0d3c25cf159e89a2/href">https://medium.com/media/7fc5172199ad0fef0d3c25cf159e89a2/href</a></iframe><p><strong>Scenario 3:</strong> The feature exposes an Activity for a certain UI flow.</p><p>To implement the third scenario, we can either make the feature satellite expose an Intent-Filter through the AndroidManifest that matches a certain deep-link configuration, or we can follow the same capability-driven approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59c272da634c00037263b0dd48aa297a/href">https://medium.com/media/59c272da634c00037263b0dd48aa297a/href</a></iframe><p>Again within our feature module we’d provide an implementation that simply starts the activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/034221c7ef9d6fe4111203d6b7ee8de1/href">https://medium.com/media/034221c7ef9d6fe4111203d6b7ee8de1/href</a></iframe><p>This capability is simply a wrapper around the Activity start. It defers the responsibility of locating the target Activity and instantiating the Intent to the capability’s implementation, thus keeping the base application (or other feature) clean of the implementation details. The actual feature would be within the Activity&#39;s scope — it can guide the user through a sign-up process or simply display information. All the base application cares about is that the capability is available and executed.</p><p>Each of these interfaces has to be made available in the application’s scope. The interfaces can be for example in the app module or to follow separation of concerns more strictly we can extract them into a capability layer next to the common module layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*zJF21yVvDAvDissyikbjoA.png" /></figure><p>The application (or base module) knows about (i.e. has a compile-time dependency) which capabilities are in the scope of the project. It knows about interfaces, and how to use capabilities — but it doesn’t know where / if these capabilities are implemented.</p><p>To find available implementations we can use multiple approaches. The first one would be to fall back to a <a href="https://docs.oracle.com/javase/tutorial/ext/basics/spi.html#the-serviceloader-class">ServiceLoader</a> . A <a href="https://docs.oracle.com/javase/tutorial/ext/basics/spi.html#the-serviceloader-class">ServiceLoader</a> finds, loads and assists in the usage of services within the application. The discovery is executed on-demand. If the application needs to be aware of a newly loaded module it has to poll for implementations of a capability in a certain interval or execute the discovery whenever the user wants to execute one of the capabilities.</p><p>Moving on from the approaches offered by Java we also have some options provided to us by the Android SDK. Within an Android application there is a central (merged) way of declaring the application’s services: The Android manifest. It contains a list of Activities, Services, Providers (and a lot more). Modules can expose their own manifest, which will be merged into a master manifest either during compile-time or once the module is loaded.</p><p>We can now add Intent-Filters to expose certain actions or UI elements and make them accessible via for example deep linking or we make use of other Android features. Our goal is to inject the capability into the application. The application already knows there is for example a GreyscaleBitmapCapability interface. What it doesn’t know is if and where the implementation of this interface is. So whenever the feature satellite that implements this interface is loaded into our application, we want to be aware of the implementation it provides. Within our application we create a capability registry. The application is accessible from all feature satellites which means they can inject themselves and their capabilities into the registry without additional dependencies.</p><p>For the injection of our capabilities we will fall back to the Android component ContentProvider. It can be used to capture the start point of an application (or of a feature satellite).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c1f0704cf8e58ea22205d4e2a5a875c/href">https://medium.com/media/3c1f0704cf8e58ea22205d4e2a5a875c/href</a></iframe><p>By using a ContentProvider we have switched from a capability polling system to a push-based system. Whenever a new feature satellite is loaded and offers a new implementation of a capability it simply registers itself within our registry. Other satellites (or the application’s base) can register listeners in the registry to be notified of changed capability implementations.</p><p>The ContentProvider approach is already in <a href="https://firebase.googleblog.com/2016/12/how-does-firebase-initialize-on-android.html">use within the Firebase SDK</a>. In the blog post, the following reasons are stated:</p><blockquote>1. They are created and initialized (on the main thread) before all other components, such as Activities, Services, and BroadcastReceivers, after the app process is started.</blockquote><blockquote>2. They participate in manifest merging at build time, if they are declared in the manifest of an Android library project. As a result, they are automatically added to the app’s manifest.</blockquote><p>Also stated in the blog post is one of the drawbacks of the ContentProvider approach: If one of the Android components within the application are running in another process, that process doesn’t create ContentProviders, thus the approach will not work in multi-process applications.</p><p>There are multiple approaches to modularize Android applications — most of them have limitations or drawbacks. All of them aim to reduce the code’s complexity and to make working on the codebase, especially long-term, easier. As a starting point it makes sense to modularize by layers and features. Identify core-parts of your application and extract them into smaller modules to make them more maintainable. In an existing application or with a small development team there may not be enough time or capacity to refactor the application into smaller feature satellites, but luckily this is not needed. New features can be built as satellites if the foundation of the application has already been modularized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*893qVRF99TExIZwwXhBEBw.png" /></figure><p>If a core and a common layer have successfully been identified, it is easy to add feature satellites outside of the current application’s scope. With minimal changes in the application setup — setting up the registry for feature satellites and a capability handling system — it is already possible to utilize feature satellites.</p><p>If you are interested in feature satellites and seeing a repository with this already set-up, check out my GitHub repository:</p><p><a href="https://github.com/damian-burke/android-dynamic-feature">damian-burke/android-dynamic-feature</a></p><p>I’m always interested in discussions about this topic, feel free to contact me on twitter or post a comment below.</p><p><a href="https://twitter.com/damian2048"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15453f3d7940" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/inverting-the-dependency-independent-features-in-android-applications-15453f3d7940">Inverting the Dependency — Independent Features in Android Applications</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving towards a Micro-Service Mindset on Android]]></title>
            <link>https://proandroiddev.com/moving-towards-a-micro-service-mindset-on-android-910de7e4f0c2?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/910de7e4f0c2</guid>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 07:05:20 GMT</pubDate>
            <atom:updated>2019-07-07T17:56:47.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*6OieQk6y_gOuTYlQ.jpg" /></figure><p>Most Android applications are built as <strong>monoliths</strong>.</p><blockquote><em>In software engineering, a monolithic application describes a single-tiered software application in which the user interface and data access code are combined into a single program from a single platform. A monolithic application is self-contained, and independent from other computing applications. </em><a href="http://(https//en.wikipedia.org/wiki/Monolithic_application)"><em>(Source)</em></a></blockquote><p>As a software engineer, you are most likely to work on different projects. If you work on a small or medium scale project, you will probably have a single module. If you work on a larger project, you most likely have more than one module in your project. You either have modules defining the vertical layers (like api, data, domain, ui) or you took a more horizontal approach and have feature modules. You may or may not have a certain set of core modules on which your other modules depend, but you most likely only have a single app module. Usually there is a single APK — a single entry point through an icon displayed in the launcher, and looking under the hood we can spot an app module that houses this entry point and connects the dots. For most applications, this works out just fine. If you create a new project with Android Studio it also creates an app module for you to host your application’s code-base, pointing you towards this direction.</p><p>While a monolithic architecture is not necessarily a bad thing, in this post we are going to take a look on <strong>why some applications should move away from a monolithic structure</strong>, <strong>how this can be achieved</strong>, and <strong>both advantages and disadvantages</strong> of these approaches.</p><h3>Different Perspectives</h3><p>Software engineers have been trying to move away from monoliths for a couple of years now. The most visible migration away from a monolithic architecture happens in backend with the move towards micro-services. <strong>Micro-services operate with limited responsiblities and a fixed scope.</strong> Between these services communication happens through well-defined interfaces over implementation-agnostic transfer layers (for example HTTP requests or WebSockets).</p><p>There are multiple advantages of a service-oriented architecture. To keep it short, here’s a list of a couple of them:</p><ul><li>Scalability</li><li>Agility</li><li>Fault Tolerance</li><li>Software Stack Agnostic</li><li>Clear Separation of Business Concerns</li><li>Faster Development</li><li>Faster Deployment</li></ul><p>Of course monolithic architectures also have their advantages — it’s not all “bad”:</p><ul><li>Single Deployment Unit</li><li>All Code in one Place (which is nice for humans and IDEs)</li><li>Majority of Apps built like that (a lot of resources, tutorials, …)</li></ul><p>Taking a first look at these lists, they seem to apply mostly to backend systems. Mobile applications are built “completely different”, so why should any of this apply to mobile development? Actually, <strong>most of the above listed benefits translate to mobile</strong> pretty well. Service-oriented architectures are well suited for<strong> growing engineering</strong> <strong>teams</strong> and a <strong>growing feature count</strong>.</p><p>Just taking a look at Android in the last couple of years the most obvious changes are the technologies used:</p><ul><li>Java / Kotlin</li><li>Design Pattern (MVC, MVP, MVVM, MVi, …)</li><li>Multi-Threading (AsyncTask, Loader, RxJava, Coroutines, …)</li><li>Database (raw SQLite, GreenDAO, Room, …)</li><li>Android X (Architecture components, Navigation, …)</li></ul><p>The Android eco-system is <strong>moving rapidly and is not afraid to pivot</strong>. A monolithic architecture forces the engineers to agree on a certain tech stack — due to the dependency. In a service-oriented architecture, each service can be flexible. This can of course be seen as both an advantage and disadvantage. On the one hand it doesn’t force engineers to use the (maybe deprecated) tech stacks of their predecessors, on the other hand it can lead to <strong>very</strong> different engineering approaches being used. But with communication within the team, this should be an easy problem to solve.</p><h3>Monolith and Modularization on Android</h3><p>An Android application built as a monolith can be identified by having <strong>an app module on the top of the dependency chain</strong>. If your project has vertical layers as mentioned earlier, it’s a monolith. If it’s built with horizontal layers (feature-modules), and the app module on top has a dependency on all feature modules, it’s a monolith. Most of the applications will have one of these approaches. It’s the easiest way to set up your application, it allows for a straight-forward navigation pattern througout the application (as all parts of the app are known due to the dependency chain), and it makes sense from a conventional point of view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*rgXqXgX7YCr06t6s_IXAMg.png" /><figcaption>Monolithic Dependency Graph</figcaption></figure><p>A non-monolithic Android application would look a bit different. There is <strong>no longer an app module on the top of the chain</strong>. There is no module that has god-like knowledge about all features, instead features are built in an independent way. The app is built on a need-to-know basis — which makes a lot of sense. Every feature module (or feature module-tree) only knows what it actually requires for its functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*zfnRuhuZFLv6A2HcSjp7PA.png" /><figcaption>Dependency Graph with Feature Satellites</figcaption></figure><p><strong>Since the application will still run in a single process on the device, there is still the need to connect the dots and to combine all of these modules into an actual application.</strong> Features need to be able to navigate between each other, data has to be transferred between them, and backstacks have to be provided to ensure proper navigation throughout the process lifecycle (and beyond that, once the process has been killed and the app is recreated).</p><p>Splitting the application into feature satellites working on a need-to-know basis, <strong>one of the things we still have to think about is navigation</strong>. In a monolith navigating between features is pretty simple due to classes and features being known at compile-time. In a service-oriented architecture, this is not given, thus navigating by classes doesn’t work. An easy solution would be to rely on fully qualified class names (com.brainasaservice.app.feature_service.MyActivity) and rely on reflection — but that feels a bit dirty.</p><p>Thinking back to microservices, an implementation-agnostic way to navigate would be the way to go: <strong>Deep Linking</strong>. <a href="https://blog.usejournal.com/navigation-in-modular-applications-with-deep-linking-6a599c11e487">Just recently, I have published a post with more detailled and thorough thoughts on why deep linking is a good candidate for navigation in modular applications.</a></p><p><strong>Deeplinks are supported natively by the system.</strong> They require no tight coupling between components, as feature satellites / services can simply register themselves as processors for certain schemes. Deep Links are capable of transmitting data, <a href="https://tools.ietf.org/html/rfc3986">there is a well-defined scheme</a>.</p><p>With the advancement of Android X and the architecture components, we also get access to the navigation component, which coincidentally also supports deep linking out of the box.</p><h3>Feature Satellites</h3><p>In a service-oriented architecture, each feature acts as a (micro-) service. Each of these services exposes its set of capabilties, making itself discoverable.</p><p>For example in a car-sharing application, you’ll have a service-module that enables Bluetooth communication, so the service exposes itself with a capability to communicate with certain vehicles through Bluetooth. Devices that don’t have a Bluetooth chip don’t need to load the Bluetooth communication service — with a service-oriented architecture, they simply don’t.</p><p>In a video-streaming application you might have a couple of different video players, each with different sets of capabilities. One of them consumes MP4 files, another one can consume HLS streams. Again, each of these services exposes its capabilities and they can be loaded on-demand.</p><p>Going back to the beginnings, our app module would act as a service registry. Each feature registers themselves as available (with their certain set of capabilities) once they are loaded. The app module serves as a broker that manages the application’s process, but delegates the actual UI and/or functionality to the feature satellites. It also handles the on-demand processing and downloading of feature satellites.</p><p>I published a repository on GitHub that shows an example of a service-oriented architecture. Feature modules are treated as services that provide a configuration and a certain set of capabilities to the application, instead of being referenced directly through the app module.</p><p>Keep in mind that it’s very basic — it provides a sample of three different service modules that provide different services — ranging from providing UI elements, hosting their own Activity to simply offering image processing. Each service injects its own configuration into a registry hosted by the app module, thus making it available.</p><p>The service modules thus offer a limited API or set of entry points (the capabilities) to the application, leaving the rest as implementation detail.</p><p><a href="https://github.com/damian-burke/android-dynamic-feature">damian-burke/android-dynamic-feature</a></p><h3>Google’s Dynamic Delivery</h3><p>The <strong>Google Play Store</strong> recently started to point developers into a service-oriented direction. Starting with <a href="https://developer.android.com/platform/technology/app-bundle">App Bundles </a>— Google’s approach to separating resources — Google now presented <a href="https://developer.android.com/studio/projects/dynamic-delivery#dynamic_feature_modules">Dynamic Delivery</a> — enabling developers to download service / feature modules during runtime.</p><p>With dynamic delivery, modules are declared as onDemand. This feature is available starting with Android 5.0 (API 21). If an application supports earlier versions of the OS, a compatibility setting (fusing) can be used to include or exclude the feature for these builds.</p><h3>To Be Continued</h3><p>With more diverse code styles becoming possible in the Android ecosystem, it becomes more important to add modularization to a certain degree to applications. Companies at scale —<a href="https://instagram-engineering.com/app-modularization-and-module-lazy-loading-at-instagram-and-beyond-46b9daa3fea4"> for example Instagram </a>— have been doing it since a couple of years already and heavily rely on hot loading feature modules during runtime (<a href="https://github.com/Instagram/ig-lazy-module-loader">they also open-sourced the lazy module loader on GitHub</a>). Now, Google offers its own solution to tackle the problem and to allow applications to be built for billions of users.</p><p>Even though Google supplies us with a way how to load features on-demand, it is still a topic of discussion on how to properly include these features into the codebase.</p><p>If you already have some experiences with loading features on-demand, hot loading code — with Google’s dynamic delivery feature or maybe even with Instagram’s Lazy Module Loader let us know in the comments. If you made experiences with feature discoverability, navigation patterns or in general — feel free to share.</p><p>If you liked this post, want to discuss it or simply stay in the loop — follow me on <a href="http://twitter.com/damian2048">twitter</a>:</p><p><a href="https://twitter.com/damian2048"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=910de7e4f0c2" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/moving-towards-a-micro-service-mindset-on-android-910de7e4f0c2">Moving towards a Micro-Service Mindset on Android</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation in Modular Applications with Deep Linking]]></title>
            <link>https://medium.com/@burkedamian/navigation-in-modular-applications-with-deep-linking-6a599c11e487?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a599c11e487</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 22:20:30 GMT</pubDate>
            <atom:updated>2019-07-07T17:57:44.153Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><p>As time goes by applications tend to grow. Growing from a minimum viable product (MVP) to a feature-rich product is an exciting phase in each company/startup — both from a business as well as from a development point of view.</p><p>If you’ve started as a sole developer or in a team of two it is very likely that you have a good understanding of the code base. You know the architecture, you are familiar with design patterns and the choices that were made. You are able to split tasks between your teammates based on which parts of the code base they touch to minimize conflicts in your work.</p><p>As the number of developers grows, it makes sense to split the responsibilities and/or parts of the app and divide them between the groups. If your application has a certain set of features or if you’re going for a growth vs. retention split doesn’t matter. Looking at the code base it is easy to identify a certain set of layers, which (if we look at vertical layers) could look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*bbJEu_iLb3h9GmumBDtVDA.png" /><figcaption>Example of a vertically layered software architecture.</figcaption></figure><p>For smaller teams it is perfectly fine to work on a code base like this. As the team grows, more and more conflicts will happen during development and the need for additional separation will come up. This is usually where the switch from layer-based packaging to a feature-based packaging or modularization comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TP2Yb3bHKDW709mHjRkSwQ.png" /><figcaption>Introducing horizontal layers</figcaption></figure><p>Implementing horizontal layering on top of a certain set of core modules. This means that a feature module contains all code related to the feature, from the data layer to the presentation and view layers. This allows developers to work on features independently, most of the time without the need to work on code outside of their scope.</p><h3>Navigation in Android Applications</h3><p>Navigation in Android apps is usually pretty straight forward. If you have multiple Activities, you simply create an Intent for the targeted Activity, add some extras and start it through the available Context object. If your application is Fragment-based with a single Activity its even simpler — just replace the Fragment.</p><p>These approaches have a certain drawback: They require tight coupling of the components. If you have a main Activity which is supposed to start a detail Activity, it has to know about the location of the detail Activity’s class. If you abstract this into a Navigator class the implementation of this class needs to know about all possible screens.</p><p>Splitting the app horizontally means we want to remove dependencies between the modules. Standard navigation in Android requires tight coupling, meaning each module is required to know about other modules that are going to be available through navigation.</p><h3>Solution Requirements</h3><p>Trying to find a solution that is more suitable for an increased team size, we can come up with a couple of requirements.</p><h4>Flexible</h4><p>We want to be flexible and support multiple types of navigation:</p><ul><li>Intent-based navigation for multiple Activities</li><li>FragmentTransaction-based navigation for single Activity</li><li>Other types of navigation (for example for View-based applications)</li></ul><p>Parsing and processing the links should be independent from the actual navigation. Our processing should happen in a separated layer and delegate the actual navigation to a different party.</p><h4>Decentralized Processing</h4><p>Since the goal is to allow teams to work independently we want to avoid having a centralized link parser. We want each module to be able to supply the application with module-relevant link parsing and navigation events.</p><h4>Dynamic</h4><p>Thinking about A/B testing and dynamic feature loading it would be beneficial to be able to register (or unregister) link processors in runtime. Google has announced <a href="https://developer.android.com/studio/projects/dynamic-delivery">dynamic feature modules</a> which would play together with this.</p><blockquote>Dynamic feature modules allow you to separate certain features and resources from the base module of your app and include them in your app bundle. Through Dynamic Delivery, users can later download and install those components on demand after they’ve already installed the base APK of your app.</blockquote><p>Once a deeplink for a dynamic feature is processed, the app can either trigger the download of the feature module or if it is already present, simply execute the navigation action.</p><h3>The Deeplink Approach</h3><p>Looking for an alternative approach to navigation, deep linking comes to mind. Most applications require deep linking at some point to redirect the user to certain points in his journey or to point the user towards certain actions so utilizing deep linking for general navigation within the app makes sense.</p><h4>Why use Deep Linking?</h4><p>Deep Linking is a platform-independent approach. Android, iOS and web apps can use them. Links are a specified format that offers a lot of customization and an easy way to pass information through schemas, hosts, path segments and queries. This again has multiple benefits, it allows for scoping by feature-path and semantic linking (human readable URIs).</p><h4>Example Implementation</h4><p>The basis for our deep linking will be a DeeplinkHandler interface, which does nothing except</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f60f1400fb6c6d1c2f19122a08a673dd/href">https://medium.com/media/f60f1400fb6c6d1c2f19122a08a673dd/href</a></iframe><p>An implementation of the DeeplinkHandler interface that is able to handle multiple DeeplinkProcessors looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a088b7256946f08057e0ff1a5af44ba3/href">https://medium.com/media/a088b7256946f08057e0ff1a5af44ba3/href</a></iframe><p>The DefaultDeeplinkHandler loops over a Set of DeeplinkProcessors, searches for a processor that matches the input and executes the processor if found. If no matching processor is found, it returns false to indicate that the link could not be processed.</p><p>The DeeplinkProcessor interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1c982235efd7756227fadd27fd759e/href">https://medium.com/media/ed1c982235efd7756227fadd27fd759e/href</a></iframe><p>For convenience and standardization it exposes an EXTRA_KEY constant, which can be used to store data (for example a Parcelable) in the navigation action.</p><p>A simple example implementation that does nothing except for matching for a link and starting a certain Activity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1fc3298b21ae9535bd63900ee40fdaa/href">https://medium.com/media/a1fc3298b21ae9535bd63900ee40fdaa/href</a></iframe><p>An instance of this processor will be passed to the default DeeplinkHandler instance to enable matching and processing the links. This processor matches any link that contains the keyword deep/content and starts the DeepContentActivity.</p><p>Intents allow us to also pass data. If we construct a link with variables, for example a name, we can extract it from the link for example through String operations or by parsing the link into URI objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24e4aeb530a5859bf26d2e4bda0cd3e/href">https://medium.com/media/d24e4aeb530a5859bf26d2e4bda0cd3e/href</a></iframe><p>This processor matches links that contain deep/custom/. If a matching link is found, the prefix consisting of the schema, host and first path segment deep://deep/custom/ will be removed from the String. The first remaining path segment will be consumed as a name variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b77abb2f55a3aa1834ae1eb5b1afe3ac/href">https://medium.com/media/b77abb2f55a3aa1834ae1eb5b1afe3ac/href</a></iframe><p>The name will be passed to a CustomDeeplinkModel (Parcelable) which will be added to the created Intent — and will be consumed by the started Activity.</p><p>This very simple setup allows us to dynamically add DeeplinkProcessor instances. Each instance is able to handle certain links and to execute certain navigation actions. The processor implementations in this example hold a reference to the application’s Context. If for example navigation actions should be done through fragment transactions, the processors could also hold a reference to a FragmentManager or simply emit navigation events to a navigation delegate that keeps track of the FragmentManager.</p><p><a href="https://github.com/damian-burke/android-deeplink-navigation">damian-burke/android-deeplink-navigation</a></p><p>To be able to process all incoming deeplinks, an entry in the AndroidManifest.xml is required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d4b6cbc13a9f49a86cb5e030d832bea/href">https://medium.com/media/8d4b6cbc13a9f49a86cb5e030d832bea/href</a></iframe><p>The referenced Activity extends our DeeplinkActivity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/502720e6ccb57d0f4c61b009dd6815e1/href">https://medium.com/media/502720e6ccb57d0f4c61b009dd6815e1/href</a></iframe><p>And provides the DefaultDeeplinkHandler in the implemented getDeeplinkHandler function.</p><h3>Connect the Dots with Dagger</h3><p>A simple way to utilize Dagger is to Bind each DeeplinkProcessor into a Set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/444198c88e58d5388d2646935c682609/href">https://medium.com/media/444198c88e58d5388d2646935c682609/href</a></iframe><p>This can be done from different modules with as many processors as required. To utilize the Set simply create the DeeplinkHandler through Dagger as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58780ad5d2d89504c1ab251f8665a3ed/href">https://medium.com/media/58780ad5d2d89504c1ab251f8665a3ed/href</a></iframe><p>Each feature module can now expose its DeeplinkProcessor implementations through a Dagger module, and they will automatically be included in the Set consumed by the DeeplinkHandler.</p><p>This of course requires each feature module to have Dagger as dependency and to expose a Module to the Component.</p><h3>Alternatives</h3><p>There are a couple of libraries published on GitHub that allow you to utilize deep linking-based navigation. For example <a href="https://github.com/airbnb/DeepLinkDispatch">DeepLinkDispatcher by airbnb</a>.</p><p>The Navigation Android Architecture Component also <a href="https://developer.android.com/topic/libraries/architecture/navigation/navigation-deep-link">supports deep linking</a> b̶u̶t̶ ̶a̶t̶ ̶t̶h̶e̶ ̶m̶o̶m̶e̶n̶t̶ ̶i̶t̶ ̶i̶s̶ ̶s̶t̶i̶l̶l̶ ̶i̶n̶ ̶a̶n̶ ̶A̶l̶p̶h̶a̶ ̶v̶e̶r̶s̶i̶o̶n̶ which will most likely see a stable release soon.</p><p>If you liked this post, want to discuss it or simply stay in the loop — follow me on <a href="http://twitter.com/damian2048">twitter</a>:</p><p><a href="https://twitter.com/damian2048"></a></p><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2IVAl0TbsfES9cFGYr40g.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_read_later_text">Journal</a>.</p><p>🗞 Wake up every Sunday morning to the week’s most noteworthy Tech stories, opinions, and news waiting in your inbox: <a href="https://usejournal.com/newsletter/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=guest_post_text">Get the noteworthy newsletter &gt;</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a599c11e487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Testing Custom Views on Android]]></title>
            <link>https://proandroiddev.com/an-introduction-to-testing-custom-views-on-android-10a6152f379?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/10a6152f379</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Tue, 08 May 2018 21:53:06 GMT</pubDate>
            <atom:updated>2019-07-07T17:57:05.083Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re working on a large app, your product designers have extraordinary wishes or you just like to split your app into small modules to ensure maintainability and separation of concerns — you’ll most likely end up implementing custom views at some point.</p><p>Writing a custom view is pretty easy. You can for example <strong>extend android.view.View </strong>or you can <strong>extend your favorite layout like a FrameLayout </strong>and inflate the XML for your custom view. Instead of including the whole view hierarchy in your layout files, all you have to do is include the custom view and use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10fccab9ceb7ea98d1fb53035391cab/href">https://medium.com/media/f10fccab9ceb7ea98d1fb53035391cab/href</a></iframe><p>Writing a custom view to encapsulate certain functions makes sense. Not every custom component has to be an Activity or Fragment. Smaller modules mean less responsibility and thus less room for errors. To further reduce errors, we are going to add some tests to ensure that everything is working as intended — i.e. the state is processed correctly.</p><p>Thinking about<strong> testing a custom view</strong>, you’d most likely consider <strong>UI tests with Espresso</strong>. UI tests are pretty <strong>cost intensive.</strong> It takes time to write them properly and it takes time to execute them, since you’ll need to boot an emulator or install on a physical device. To reduce both the time we have to spend writing the test and the time it takes to execute it, <strong>we’ll shift most of the testing into our unit test layer</strong>.</p><p>However, since at the moment our custom view class is just extending <strong>android.view.View</strong> or a layout, there’s no practical way to do this. Luckily, architectures like <strong>MVP </strong>and <strong>MVVM </strong>are not required to be used with Activity and Fragment exclusively. It’s just as easy to implement these architectures in custom views, to separate logic from the view itself — resulting in a <strong>unit-testable logic layer</strong> and a <strong>UI-testable view layer</strong>.</p><p>Let’s think about a custom view that is used to display the current user’s state. The view is supposed to display an image (the user’s avatar) and their given username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-tQmqi98a2pQJIBjNq7SqA.png" /></figure><p>Since not every user of our app will be logged in, we’ll also need a logged-out state. Also, we’d like to have a verified userbase, so we’ll require a verification of the user’s email address which we will display with a small badge.</p><p>Identified view states:</p><ul><li>Logged out</li><li>Logged in (verified, verification pending, verification required)</li></ul><p>This state directly depends on the user’s account. In our case, the account data class looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c132e484bb03535dc466b15b78a37709/href">https://medium.com/media/c132e484bb03535dc466b15b78a37709/href</a></iframe><p>To differentiate between a logged out user and an active user, we’ve implemented a sealed class encapsulating both of them.</p><p>In a barebones custom view, we’d pass in the name, avatar and activated field (with an option to set the view to its logged-out state).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7240ae5ccb49d52b54607576eb2e1a/href">https://medium.com/media/2a7240ae5ccb49d52b54607576eb2e1a/href</a></iframe><p>The custom view would then put these values into their respective text fields and display the right avatar or it would show the logged-out state. Since these methods are all <strong>operating on the custom view itself</strong>, it requires us to write <strong>UI tests</strong> to verify the behavior.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2700ee855258d2a7b96e09aabc88b53a/href">https://medium.com/media/2700ee855258d2a7b96e09aabc88b53a/href</a></iframe><p>Before jumping into the tests, lets take a look at our custom view and refactor it a bit. For a quick example, we’ll refactor the view by utilizing <strong>MVP</strong>.</p><p>Identifying our <strong>model</strong> is quite easy: the Account.</p><p>Identifying the <strong>view</strong> is simple as well: It’s our custom view, but without the logic. Reducing the view to simple setter methods manipulating the state, we have to identify possible <strong>entry points into the view state</strong>. Our view contains a couple of components:</p><ul><li>TextView for the username / logged out text</li><li>ImageView for the user’s avatar / logged out avatar</li><li>ImageView to show activated / pending state</li></ul><p>For each of these possible states we’ll create a method in our View interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1618b7efb87ec66196ec7b19a7c294d7/href">https://medium.com/media/1618b7efb87ec66196ec7b19a7c294d7/href</a></iframe><p>Our <strong>Presenter</strong> is going to be pretty straightforward, all it does is care about the view’s lifecycle (subscribing to data sources and handling its teardown by unsubscribing):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22fee99a721dc438256555e2e516c60d/href">https://medium.com/media/22fee99a721dc438256555e2e516c60d/href</a></iframe><p>The first steps towards a testable custom view are done. We have successfully identified our <strong>entry and exit points </strong>between the logic layer and the view layer.</p><p>The next step is to actually refactor and/or implement our newly created interfaces. To keep it short, we’ll skip that — though if you’re interested, a full implementation can be found in the linked GitHub repository at the bottom.</p><p>Finally we can start writing some tests. We’ll start off with our <strong>unit tests</strong> to verify our logic and behavior. Our logic is in our presenter class.</p><p>For our unit tests, we’ll use the following dependencies:</p><ul><li>JUnit</li><li>Mockito</li><li><a href="https://github.com/nhaarman/mockito-kotlin">Mockito-Kotlin</a></li></ul><p>To start, we’ll define the mock objects we’ll use in our test as well as a setup-function to initialize our mocks and our presenter before each executed test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acf862b60158e3cdee928131951f80d5/href">https://medium.com/media/acf862b60158e3cdee928131951f80d5/href</a></iframe><p>Each of our tests will only cover a single verification, to allow us to identify failures as small-grained as possible. This will allow us to spot bugs and their scope easily. Before writing unit tests, we’ll identify possible states, possible interactions with the presenter and how they are going to affect our view.</p><p>An incomplete list of possible things to test (the full list is in the repository):</p><ul><li>logged out account hides badge</li><li>active account sets name</li><li>active account sets avatar</li><li>active account with pending activation shows badge</li><li>…</li></ul><p>Each of these test cases is simple. Writing the tests will not take much of your time, but the more the project grows, the more valuable they will become. This is especially true as more developers work on the project concurrently.</p><p>An implementation of these tests could look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65c09ff035bd6e568d8a454c494d995d/href">https://medium.com/media/65c09ff035bd6e568d8a454c494d995d/href</a></iframe><p>Notice that:</p><ul><li>Everything except for our test target (the presenter) is a mock</li><li>The presenter uses a data source to receive the data, which we can manipulate to trigger different states (logged in, logged out, …)</li><li>Each test verifies a single behavior for a specified set of conditions</li></ul><p>Now that we’ve covered the logic side of our view, its time to take a look at <strong>UI tests</strong>. For the UI tests, we’ll use <strong>Espresso</strong>. With Espresso, we can verify our UI’s behavior. For example, that certain views are visible and contain the information they should contain at the right times. In Espresso tests, we can simulate certain user behaviors like tapping on buttons, swiping left and right or typing text. We can then check if the view is behaving correctly.</p><p>Espresso provides test rules to start Activities which are being tested. However, since we are focusing on custom views, we don’t really want to start the Activity our view is contained in, since that would be overkill. Ideally, we’d like to have the custom view separated to allow us to completely focus on the view itself, without distractions.</p><p>To achieve this, you might add a mock build flavor to apps which contain utilities for testing views (and Activities / Fragments). Doing this is pretty simple. Just change your module’s build.gradle and add the flavor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0765673e38134f6278cd7b2df8f822a1/href">https://medium.com/media/0765673e38134f6278cd7b2df8f822a1/href</a></iframe><p>In this example, the mock flavor will be used to store mock data sources, as well as our test utilities. The prod flavor (production) will contain the “real” implementations. Separating these with flavors offers a big advantage: none of your mocked code will appear in the compiled binary of your production application— it’s a separated environment.</p><p>Our view’s data source provides us with the user’s account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3f8dc56f8d0f8abac56a26a63c97ca/href">https://medium.com/media/5c3f8dc56f8d0f8abac56a26a63c97ca/href</a></iframe><p>In our <strong>production flavor</strong>, we’ll prepare the implementation of this interface and inject it into our custom view’s presenter. In our<strong> mock flavor</strong>, we can implement a mocked version of this which allows us to prepare and change the returned account at runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5043286458b408064e45cc4162ec0f36/href">https://medium.com/media/5043286458b408064e45cc4162ec0f36/href</a></iframe><p>Now, we still need a way to test our custom view with Espresso. For that, we’ll create a MockActivity<strong> </strong>in our mock flavor, which we can (just like the data source) manipulate before and during runtime. To display our custom view, we’ll need to be able to <strong>either change the used layout resource or to directly inject our view into the Activity before it is created</strong>. For this example, we’ll use a layout file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b8f214ca2fb35ef016eb6a230f5fe84/href">https://medium.com/media/8b8f214ca2fb35ef016eb6a230f5fe84/href</a></iframe><p>We’re all set-up, now it’s time to finally test our custom view. We’ll create a class in our androidTest directory, and set-up the ActivityTestRule<strong> </strong>for our MockActivity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/087cb3ae4b7afb55fa994340eb5d78e0/href">https://medium.com/media/087cb3ae4b7afb55fa994340eb5d78e0/href</a></iframe><p>Our MockActivity relies on us providing a layout resource ID, which will then be used to set the Activity’s content view. In our test, we’ll just wrap our custom view in a layout. The XML file is created in the <strong>mock flavor’s resource folder</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d64590e58b3851d494c41f92f801151/href">https://medium.com/media/9d64590e58b3851d494c41f92f801151/href</a></iframe><p>Coming back to our AccountViewTest, we’ll now set the MockActivity’s layout resource ID to our newly created one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/563dc8cd5de272b01d485e7d60755cd3/href">https://medium.com/media/563dc8cd5de272b01d485e7d60755cd3/href</a></iframe><p>Now, each time we start our Activity with our ActivityTestRule, it’ll inflate our mock XML layout, thus display our custom view. Together with our mocked data source, we’re now able to manipulate the view’s state and test and verify its behavior.</p><p>An example of a single Espresso UI test with our MockActivity, a mocked data source and our custom view in a mock-only XML layout file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebcb45c61488082df25b7a791bd521d0/href">https://medium.com/media/ebcb45c61488082df25b7a791bd521d0/href</a></iframe><p>This will successfully start up the Activity, display our custom view, set the provided account state to LoggedOut and verify that the displayed username matches our logged-out string as well as that the account validation badge is hidden.</p><p>In summary, this is quite a nice way to increase test coverage without too much complexity. Once the setup is prepared, it takes minimal effort to create UI tests for custom views, which can be verified and manipulated easily.</p><p>Combining this setup with a library like <a href="https://github.com/square/spoon">spoon</a> will enable you to easily take screenshots and create informative test reports. This will not only help you find errors in added code, but also help product designers verify UI behavior on different devices, screen sizes, languages, etc.</p><p><strong>Below this, you will find a link to a GitHub repository I’ve set up with a full example of a custom view with unit and UI tests.</strong></p><p><a href="https://github.com/damian-burke/android-custom-view-testing">damian-burke/android-custom-view-testing</a></p><p>If you liked this post, want to discuss it or simply stay in the loop — follow me on <a href="http://twitter.com/damian2048">twitter</a>:</p><p><a href="https://twitter.com/damian2048"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10a6152f379" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/an-introduction-to-testing-custom-views-on-android-10a6152f379">An Introduction to Testing Custom Views on Android</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing on Android with a clean Architecture]]></title>
            <link>https://medium.com/@burkedamian/a-b-testing-on-android-with-a-clean-architecture-c66c6bfd2131?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/c66c6bfd2131</guid>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Sun, 01 Apr 2018 16:31:06 GMT</pubDate>
            <atom:updated>2019-07-07T17:57:29.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*Mr6qZHx2TPCK4J1O." /></figure><p>Implementing a clean architecture is a hot topic in the development world, especially in the Android community. Using interfaces to define entry and exit points, extracting business logic, keeping the view layer as dumb as possible, dependency injection — and more. Depending on the size of the code-base, it may seem that following these architecture proposals adds overhead to achieve simple goals.</p><p>Reading through discussions about why cleaning your code-base is recommended, most of the comments will point towards increased testability. On Android it is important to keep the business logic platform-agnostic to allow testing via JUnit — instead of requiring the Android SDK — which vastly decreases the execution time.</p><p>Another benefit offered by a clean architecture is modularization. This has two main benefits: It allows to work on for example feature modules without touching the other modules, creating an independent scope to work in and thus reducing conflicts. On the other hand, due to incremental compilation, it will decrease the application’s compile time and speed up development in general.</p><p>Taking a look at a clean architecture, usually a certain set of layers emerges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*bXV_b22jDIe-PUre." /></figure><p>The communication between each of these layers is defined by interfaces, allowing to easily mock incoming and outgoing layers for unit and integration testing. On the other hand, it allows us to replace components like the presenter or the view which results in different behavior or displaying different user interfaces.</p><p>This is where it is time to think about A/B testing.</p><p>A growing user-base with good ratings indicates that people like your application, which is good. To keep your application’s growth rate stable you are most likely trying to improve your application by adding new features or improving certain flows and funnels. Stalling the application’s development allows competitors to catch up and copy — or even improve — your application’s unique selling points. In the start-up world this might become a problem. On the other hand, rushing features into your application is probably not the best idea either. Whenever adding new features, you want to make sure your user-base is actually going to accept, use and like the feature. Going back and thinking about the diversified user-base, creating features that most of your users are going to like seems to be a hard task.</p><p>This is where we will reap in the benefits of the application’s architecture.</p><p>Being able to simply swap out for example the view layer for a certain feature allows us to test our shiny, new feature. As an example, we can think of an application displaying a list of videos and allowing the user to stream them onto their phones. Initially, our screen was just that — a plain list with the video’s title and a thumbnail. This seems to work, people look at the list, they know what it is and they watch our provided videos — great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*k_Kh1xG4itUR9OLZ." /><figcaption>Our baseline. A simple list of video-titles.</figcaption></figure><p>Trying to improve the screen, we want to add video suggestions above the list — for example to drive users towards consuming our best video, our highest-rated video or simply the latest video we’ve added to our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*5crJN3mrRazEoJXu." /><figcaption>Our test variant with a recommended video on top of the list to draw the user’s attention.</figcaption></figure><p>To achieve this, we have to change our View layer. We need to add an appropriate view element into our layout to display the recommended video, as well as a method in our View interface to display the recommended video.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b30d6b28b76b2bcaaa7425e2692a841/href">https://medium.com/media/5b30d6b28b76b2bcaaa7425e2692a841/href</a></iframe><p>Also, our Presenter layer needs to be adjusted to forward the recommended video to the view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b060229dbb5556167f01ae93148a8812/href">https://medium.com/media/b060229dbb5556167f01ae93148a8812/href</a></iframe><p>Now that we’ve adapted our View interface and our Presenter, which is passing on the recommended video to the attached view, we also have to change our View implementation to reflect these changes and actually display the recommended video.</p><p>Since we want to test if our new feature improves the application’s quality, we will duplicate our previously implemented view and create a new file:</p><p>VideoListActivity.kt</p><p>VideoListExperimentActivity.kt</p><p>(To make it more obvious you can structure your experiments and their files in packages or use a more appropriate naming convention with for example the experiment’s name.)</p><p>The VideoListActivity.kt is our current implementation of the View interface. Since we have to comply to our interface, but we are not using the recommended video in this View implementation, we will implement it as a no-operation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4a1a0d6cf427222f06ec39f7cd4f17/href">https://medium.com/media/0a4a1a0d6cf427222f06ec39f7cd4f17/href</a></iframe><p>In our VideoListExperimentActivity.kt, which is our duplicated file, we want to actually display the recommended video.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f152cd2919d7785ef6c85321187505/href">https://medium.com/media/e5f152cd2919d7785ef6c85321187505/href</a></iframe><p>(In our Android application, we’d also have to adapt the layout XML file — we can either stay with one XML layout file and add the recommended video layout marked with visibility=&quot;gone&quot; — which will not trigger any measuring or rendering on the view — or we can duplicate the XML to keep a separation between experiments and our current production version. With more and more active experiments, the duplication-approach will make removing and finalizing versions easier.)</p><p>Now that we have prepared our Presenter, our View interface and both of our View implementations, we have to take care of the following:</p><ul><li>Displaying the right view</li><li>Measuring our key performance indicators</li></ul><p>Displaying the right view depends on multiple things. The first thing it depends on is how you are managing your user segmentation — there are multiple ways on how to approach this. Multiple services offer a randomized user segmentation, some offer it based on constraints (for example if a test is supposed to only be executed in certain countries or languages). For simplicity, let’s assume you are using <a href="https://firebase.google.com/docs/remote-config/">Firebase Remote Configuration</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*3Watskn-hGKlZhz6Qt_0Kw.png" /><figcaption>Creating an A/B Test (Experiment) in Firebase Remote Config. Firebase also allows us to specify how many of our total users should be included in the test.</figcaption></figure><p>In <a href="https://firebase.google.com/docs/remote-config/">Firebase Remote Configuration</a> you can create parameters for your test — in our example this will be recommended_video. Each of these keys will be evenly distributed among the users in the test segment. Other services allow to manually specify the conditions, in which case we would choose to segment users by random percentiles and split them at 50%.</p><p>In this example there are two variations of the test:</p><ul><li>baseline</li><li>recommended_video</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*iERWnp6rydUYlVdmTRYeHw.png" /><figcaption>Specifying parameters and variants for our test.</figcaption></figure><p>So we would create a control group for baselinewhich covers the first 50% of the user segment. For recommended_video, add a variant covering the other 50%. Firebase will take care of the segmentation of your users.</p><p>Firebase also allows you to specify a certain goal which will be used to calculate the winning variation of your A/B Test. Other services might not offer this service, which is why we will also cover manual test evaluation later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*saqu92-skptGXm87-dBk6g.png" /><figcaption>Defining a Goal for our A/B Test in Firebase Remote Config.</figcaption></figure><p>After fetching and activating the configuration from <a href="https://firebase.google.com/docs/remote-config/android">Firebase</a> you can retrieve the values through your firebase remote config instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5011195bfed0b3c73d39e7c97bfd4bab/href">https://medium.com/media/5011195bfed0b3c73d39e7c97bfd4bab/href</a></iframe><p>This variable will either be baseline or recommended_video. (Since we only have two cases, you could also go for a boolean in this case and simplify the procedure.)</p><p>Depending on how you are handling navigation in your application, to display the correct screen a simple check is necessary:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f62a21de11b9ab4e3eead8aa8a56114/href">https://medium.com/media/1f62a21de11b9ab4e3eead8aa8a56114/href</a></iframe><p>That’s it. Make sure to initialize your testing framework as soon as possible. If you are fetching the user’s segment on-demand from a backend or service this will result in unnecessary delays — which can have a negative impact on your application’s user experience. Firebase will take care of caching the fetched values on the device, if you are using your own solution or one that does not support this you will also have to take care of this. Depending on your use-case it makes sense to add a fallback option (for example baseline) to make sure users are not stuck in an undefined state if they have no internet connection.</p><p>At this point, we have created our test and are displaying the right view with the right behavior to our test user segment. What’s left is measuring the impact of our new feature.</p><p>To measure the impact of the feature key performance indicators / conversion events have to be defined. In the case of our video-streaming application, this might be a video view. Each time a user clicks on a video and starts to watch it, an event will be fired to an analytics service of our choice (for example Firebase Analytics, Amplitude, …). This allows us to analyze how many videos are being watched over time, but this alone does not allow us to differentiate between our test user-segment.</p><p>Each of our users is in one of our two buckets — baseline and recommended_video. These are exclusive and bound to the user (as long as the test is running), which allows us to store them as user property and send the property to our analytics service. For our test with the video recommendation, we’ll create a user property called test_video_recommendation and set the value to the Stringwe’re receiving from Firebase (baseline vs. recommended_video). Everytime we fetch and activate the remote configuration from Firebase, we’ll update the user’s property value (since it might change once the test has concluded).</p><p>The user property allows us to group our analytics data and compare them. Additional filters might give us better results, depending on the conditions we have applied within the <a href="https://firebase.google.com/docs/remote-config/">Firebase Remote Configuration</a>. In our test case, we are only utilizing the random percentiles, which means the only choice we have is to filter by “new users” vs. “all users” (if your analytics service doesn’t provide this, you could also use a sign-up or onboarding event to determine if a user is a “new user” or not). Our feature is supposed to increase user engagement and retention. Since there is no clear conversion event like a purchase or subscription but instead retention is more important, we will compare all of our gathered data to determine if the test was succesfull or not.</p><p>To be able to draw conclusions from our test, we will let it run until we have achieved a certain statistical significance and trust in our results. This can be calculated with for example the <a href="https://www.kissmetrics.com/growth-tools/ab-significance-test/">significance calculator by kissmetrics</a> by entering the amount of users in your user segment and the conversion events (in our case video views).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*FR5WJmIbsYwogbdXM2CPQw.png" /><figcaption>Firebase displaying the changes towards our defined goal metric grouped by variants. In this case, our goal was “Daily user engagement”.</figcaption></figure><p>Once we have trustworthy test results, we can go back to <a href="https://firebase.google.com/docs/remote-config/">Firebase Remote Configuration</a> and send all of our traffic to the winning variation. This will instantly happen for all new users, and gradually roll out for returning users of our application due to Firebase’s caching policy (depending on your set-up).</p><p>All that’s left for us is to clean up our code — which luckily due to our architecture — is pretty straight forward. In our case, the video recommendation clearly won and increased both user engagement as well as retention. Cleaning up the code, we are removing the VideoListActivity.kt, renaming the VideoListExperimentActivity.kt to match our naming conventions, we’ll remove the original layout XML file, and remove the navigation switch for this test.</p><p>If your application reaches a certain amount of users and your team grows, you will be able to execute multiple tests in parallel by defining multiple user segments. Keeping track of running tests and removing old tests has to be an important part of keeping the code quality high — once a test is concluded all of the losing variations become “unused code” and with 10–50 tests running at the same time, some of them with significant changes throughout the different layers of your application you will be glad you have chosen a flexible architecture for the application.</p><p>You can find the complete example on my GitHub profile:</p><p><a href="https://github.com/damian-burke/ab-test-architecture">damian-burke/ab-test-architecture</a></p><p>Feel free to share your thoughts on this. If you have worked with A/B tests before, I’d appreciate if you would share your experience on separation between them with us.</p><p><a href="https://twitter.com/damian2048"></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c66c6bfd2131" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Token-based Authentication per Endpoint via HTTP Interceptor]]></title>
            <link>https://medium.com/@burkedamian/token-based-authentication-per-endpoint-via-http-interceptor-627b958c26b8?source=rss-19f55fe0f271------2</link>
            <guid isPermaLink="false">https://medium.com/p/627b958c26b8</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Damian Burke]]></dc:creator>
            <pubDate>Wed, 28 Feb 2018 13:41:19 GMT</pubDate>
            <atom:updated>2018-02-28T13:41:19.686Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost all applications nowadays are using APIs to fetch and store data. These endpoints are (hopefully) secured and require authentication to access the user’s data. A lot of these authentication methods require a token to be send alongside the original HTTP request, most likely in the HTTP header.</p><p>The token is mostly used to indicate that a user has been logged in, which will result in the backend identifying the user, checking its permissions in the database, and if everything matches accessing and delivering the requested resources.</p><p>What happens if there is no user authenticated, but data is still supposed to be available to the application? Without any authentication method, the endpoints are completely open — and (in theory) other services may access the information as well by sniffing the application’s HTTP traffic or decompiling the app itself. To avoid having the information completely in the open, an application token can be used to identify the authenticity of the application.</p><p>This increases our available tokens to two, which means we have to select which one is supposed to be injected into the HTTP request headers, which requires logic.</p><h3>The Problem</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bee88db169e19af08f404660f5052d5/href">https://medium.com/media/8bee88db169e19af08f404660f5052d5/href</a></iframe><p>Sometimes it’s a requirement to send an application-token for unauthorized requests, to make sure only users of the original application may access the API. This is supposed to make reverse engineering harder and thus protect the data. This requires some sort of management for the authentication tokens, either depending on endpoint (some endpoints require the app-token, some the user-token) or on a “highest authentication” layer (if user-token is available, send the user-token, otherwise the app-token).</p><h3>Approach</h3><p>This is an approach to simplify token-based authentication on a per-endpoint scale. It is based on OkHttp’s Interceptor interface, which allows (as the name suggests) intercepting and manipulating HTTP requests in a centralized way — which means by adding the interceptor into the OkHttpClient.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/878382a5c3046b1b326bff74291a0c41/href">https://medium.com/media/878382a5c3046b1b326bff74291a0c41/href</a></iframe><p>The purpose of this interceptor is to inject the appropriate and required header field with the user’s current authentication tokens seamlessly into the HTTP request. This is achieved by adding a placeholder header into the prepared HTTP request, which will be replaced with the actual value before being executed.</p><p>The benefits of this approach are that the actual token is not required in the API declaration scope, thus creating separation of concerns. Within the API declaration simply define the header placeholder for either the user’s token, the application’s token, or whichever you require.</p><p>The interceptor needs to be connected to anything that changes your authentication method (logging in, logging out, refreshing tokens, …). Your login procedure for example might have the following addition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c47f21ab49ed9837d607386a82f755e7/href">https://medium.com/media/c47f21ab49ed9837d607386a82f755e7/href</a></iframe><h3>Example</h3><p>In this example the endpoints require two different authentication layers:</p><ul><li><strong>Application Token</strong> in case the user is logged out to verify that the requesting application is legit</li><li><strong>User Token </strong>if the user is logged in to get access to the user’s scope</li></ul><p>The implementation of the TokenInterceptor looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f36cdf582f451099c379fa604470ca/href">https://medium.com/media/00f36cdf582f451099c379fa604470ca/href</a></iframe><p>AuthenticationInterceptor is an abstract class that implements OkHttp’s Interceptor interface. It utilizes a temporary header field (AUTHENTICATION_HEADER) in combination with a key-set. The AuthenticationInterceptor calls getTokenByIdentifier with the found header value.</p><p>Before passing through the interceptor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796522909f398adf200cd7ea3530e607/href">https://medium.com/media/796522909f398adf200cd7ea3530e607/href</a></iframe><p>This would trigger getTokenByIdentifier(identifier = &quot;User Token&quot;)which is then supposed to return the corresponding token (in this case the user’s token). The returned value is then used to replace the temporary header with the real one.</p><p>After passing through the interceptor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff5906e5346b2b8af859ef23a7f3f0d3/href">https://medium.com/media/ff5906e5346b2b8af859ef23a7f3f0d3/href</a></iframe><p>The only thing left to do is connecting the interceptor to your user authorization mechanism (login, logout). Using dependency injection and providing the interceptor implementation simplifies this task; you can either add variables or functions to set the tokens in the interceptor or you subscribe to an Observable to receive them — it’s up to you, as long as they are available whenever they are required and kept up-to-date.</p><h3>Retrofit Synergy</h3><p>If you are developing an <strong>Android application</strong> chances are high that you are also using <strong>Retrofit</strong> for your API calls. With Retrofit adding headers to endpoints is even more trivial, it boils down to adding an annotation. For this case, I have added constants to my projects which specify the required token and can simply be used within Retrofit interfaces:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/204ab10830b3f5e3318222fddc7c6dfe/href">https://medium.com/media/204ab10830b3f5e3318222fddc7c6dfe/href</a></iframe><p>The concatenation is required due to the expected format of headers Key: Value. After defining these constants, an interface for Retrofit with specific authentication requirements looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec1d9a185f03a519fefbcdcead7f02c/href">https://medium.com/media/eec1d9a185f03a519fefbcdcead7f02c/href</a></iframe><p>An example of this, including the abstract class of the TokenInterceptor can be found in my GitHub repository:</p><p><a href="https://github.com/damian-burke/authentication-interceptor">damian-burke/authentication-interceptor</a></p><p>Feel free to share your thoughts on this approach or if you have been working in environments with multiple authentication scopes before share your experiences on this topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=627b958c26b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>