<?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 Marc Neureiter on Medium]]></title>
        <description><![CDATA[Stories by Marc Neureiter on Medium]]></description>
        <link>https://medium.com/@marcneureiter?source=rss-6ea1249ace5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_ZDuE3anLTuxv1e0OPHZYw.jpeg</url>
            <title>Stories by Marc Neureiter on Medium</title>
            <link>https://medium.com/@marcneureiter?source=rss-6ea1249ace5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 22:19:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcneureiter/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[Kotlin Coroutines — why should I care about structured concurrency?]]></title>
            <link>https://medium.com/@marcneureiter/kotlin-coroutines-why-should-i-care-about-structured-concurrency-51bb1268321f?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/51bb1268321f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 10:41:43 GMT</pubDate>
            <atom:updated>2026-09-03T10:41:43.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t56UaTV2yrJvjqgf1b0olw.png" /></figure><p>Very often we get a new tool, code looks nicer and we adapt patterns that become the new standard, which is fine. Since Kotlin Coroutines was introduced nobody dares to argue with this new kid around the block, that’s for sure. But understanding the concepts thoroughly is key in order to tap into its full potential, and that’s especially true for structured concurrency.</p><p>In this blog post we’re going to dive into some small examples of how to exploit Kotlin Coroutines’ power regarding concurrent decomposition and, as small sprinkles on top, we’ll look at a nice trick to show how you can exploit the bounded nature of coroutines to your favor; and for those interested I’ll present some theoretical background in the last part.</p><p><strong>A coroutine is not a thread replacement</strong></p><p>Intuition says that if I want something to happen concurrently, start a coroutine:</p><pre>scope.launch {<br>    // do something<br>}</pre><p>A coroutine can have a start and an end just like a thread does. So what’s the difference to a thread? A coroutine can be bounded while a thread isn’t. So the real sauce is when you use that to your benefit.</p><p><strong>Show me the sauce!</strong></p><p>Let’s say we have some code that interacts with two services. The job is to retrieve account details from an account service while also doing some tracking.</p><ol><li>First, we check the account service whether it’s available.</li><li>Only if that applies,<br>• we ping the tracking service (if this doesn’t work, we ignore the failure).<br>• and we retrieve the account details of all requested accounts from the account service.</li><li>We do as many calls as possible in parallel to save time for the user.</li><li>If one call fails, all of them are cancelled<br>• and we want to return to the caller without waiting for further network responses.</li></ol><p>In Kotlin Coroutines this is how you implement that:</p><pre>suspend fun getAccountDetails(accounts: List&lt;Account&gt;): List&lt;AccountDetails&gt; {<br>    return coroutineScope {<br>       accountService.checkAvailability()<br>       launch { runCatching { trackingService.accountDetailsRetrieval() } }<br>       accounts<br>           .map { async { accountService.getAccountDetails(it.accountId) } }<br>           .awaitAll()<br>   }<br>}</pre><p>This code is short, easy to write and expressive. Just imagine you’d have to use callbacks and threads for that!</p><p><strong>Let’s break it down</strong></p><pre>accountService.checkAvailability()</pre><p>We just call this function without catching exceptions, as if an exception occurs we don’t want to continue in the flow anyway — perfect!</p><pre>launch { runCatching { trackingService.accountDetailsRetrieval() } }</pre><p>Here a coroutine is launched which attempts to ping the tracking service. We wrap the code inside runCatching { } so if something goes wrong here we ignore it — exactly as specified!</p><p>Shortly after, we call</p><pre>async { accountService.getAccountDetails(it.accountId) }</pre><p>for each account. This also launches coroutines, one for each account, meaning: all that is happening in parallel, including the call to the tracking service. This saves a lot of time, great!</p><pre>map { ... }</pre><p>What does this expression return? It’s a list of Deferred&lt;AccountDetails&gt;, each of them representing a promise to return an AccountDetails object in the future. Calling awaitAll() suspends the function until all those promises are fulfilled and returns the concrete list of AccountDetails from the backend.</p><p><strong>coroutineScope — huh?</strong></p><p>But what’s with the elephant in the room? We wrapped the whole content of the function in a coroutine Scope { } block. Why is that? The aim is to give all parallelism happening a container. That has multiple great benefits:</p><p><strong>Concurrent decomposition</strong></p><p>By using coroutine Scope { }, the suspending function can spread out to multiple concurrent execution strands. Only when the block and all started coroutines are completed, coroutine Scope { } returns. No need to manually write code that tells someone to wait. That’s all pretty convenient!</p><p><strong>Cancellation</strong></p><p>Whenever an exception happens, coroutineScope { } makes sure a sane default cancellation behavior is followed. First, it cancels all coroutines started inside it, meaning: if there are pending calls, they are ignored. Second, it re-throws the first exception that occurred. All that happens as fast as possible, no additional waiting for network responses — no time wasted!</p><p>Note, though, that cancellation is cooperative: if the underlying code doesn’t support cancellation or you use withContext(NonCancellable) { } cancellation can still take time.</p><p>I think by now it should be clear what the concept of a coroutine scope is: a way to give more complex execution flows a container, enabling convenient suspension and cancellation behavior. But:</p><p><strong>What is a </strong><strong>Job?</strong></p><p>If a coroutine scope is something that can contain work being started, a Job represents a piece of concrete work that has started at runtime. So every time you launch or async some work, a Job is created and returned immediately, although the work itself can still take some time to complete. async gets you a Deferred&lt;T&gt; that can contain a result value, but launch returns only a Job which contains no result value. Both are a kind of Job, though.</p><p>Mostly we ignore the Job returned from launch or async. So why should we be interested in it? Let’s dive into a useful example you can use in your everyday work!</p><p><strong>Excursus: exploiting Job to automate loading state</strong></p><p>Jobs contain the information whether some piece of work is finished or not. You can use this information in order to wait for completion, e.g. with join(), await() or awaitAll(). But you can also use the information in a different way: to automate updating the “loading” state of a view!</p><p>Usually, this is what you see in view models:</p><pre>data class State(val loading: Boolean, val data: String)<br><br>val state = MutableStateFlow(State())<br><br>suspend fun loadState() {<br>   state.update { it.copy(loading = true) }<br>   val data = getFromBackend()<br>   state.update { it.copy(loading = false, data = data) }<br>}</pre><p>This is error-prone:</p><ol><li>What if a colleague forgets to reset the loading state? Then the UI would be stuck in that state, rendering the UI useless.</li><li>What if an exception happens? The same mistake would happen then.</li></ol><p>Let’s imagine a tool that takes care about setting the loading state automatically, for example like this:</p><pre>async { ... }<br>    .trackWith(jobTracker)</pre><p>The idea is that the loading state is always automatically true while any job is running, no matter how many there are, even in parallel. For that, we need some utility that maintains a list of all jobs and determines its internal state by any of those jobs being active. I have created a little helper for that and called it JobTracker. And here’s how you set it up:</p><pre>val jobTracker = JobTracker { isActive -&gt;<br>    state.update { it.copy(loading = isActive) }<br>}</pre><p>Every time you start concurrent work, tie it to the JobTracker and you’re set, for example in your view model:</p><pre>viewModelScope.launch {<br>    ...<br>}.trackWith(jobTracker)</pre><p>There’s also an extension you can use in case you need to track the completion of a suspending function:</p><pre>jobTracker.coroutineScope {<br>    async { ... }<br>    launch { ... }<br>}</pre><p>The extension function simply acts like the original Kotlin coroutineScope function but additionally reports the active state to the JobTracker.</p><p>To conclude, this example demonstrates how you can effectively exploit coroutine scopes and jobs in order to not only coordinate asynchronous work but also to track it. You can have a look at this little helper <a href="https://gist.github.com/marc-neureiter/c5fb67bd275831ba7da1cd1f394d3bbb">here</a>. Feel free to use it in your code!</p><p><strong>A bit of theoretical background</strong></p><p>Why is there structured concurrency? Concurrency and asynchronicity can be messy. There are two concepts that are preceding coroutines: threads and callbacks.</p><p><strong>Threads</strong></p><p>Everyone can start threads. But coordination between them is sometimes hard. How do you make sure that, as soon as three threads are done with their jobs, the main thread confidently continues where the three other ones left off? And how to (or rather: who) makes sure those three threads are freed up after their work? All that coordination between threads is error-prone and complex.</p><p><strong>Callbacks</strong></p><p>These are one way to return to the caller, eventually handing over data. The problem is that if the consumer of some callback API forgets to wire it up correctly, it can end up with a workflow being stuck.</p><p>For example, if an exception happens in a callback or a thread, you always need to think about the correct exception handling, signalling a specific state to other threads or callbacks. Without that, the original caller of an API or thread will never know something wrong happened.</p><p>Not to mention all the annoying plumbing you need to do repetitively! So the idea with structured concurrency was to create a layer of abstraction that doesn’t deal with low-level concepts like threads and callbacks but with concepts like “branching off work” and “joining” it (alongside others like reactive flows and suspending/async functions, of course).</p><p>If you give it some thought, it’s crazy we lived with only threads and callbacks for such a long time. It is literally like using goto statements in code as we used to until the 1950s where we had no functions and return statements. Back then, if you jumped to a point in program memory, nobody ensured that the program flow would return to its origin except if you did it deliberately. As you can imagine, that was extremely error-prone. If you are interested in the analogy between using old-style threads with using goto statements, look at this great in-depth <a href="https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/">article</a> by ​​Nathaniel J. Smith.</p><p><strong>Conclusion</strong></p><p>Seeing coroutines just as a way to parallelize work is overly simplistic. Amongst other things, it’s a lightweight abstraction over threads with a structured concurrency toolset.</p><p>Coroutines are a way of modeling complex concurrent and asynchronous behavior in a way it’s easy to both read and write, dramatically diminishing the chance of unintended errors and misunderstandings. Like the old goto statements being replaced by subroutines, it’s another tool that reduces complexity for the programmer in order to be able to achieve greater functionality overall.</p><p>No matter what’s said about AI, it’s still a great time to be a programmer if you find enjoyment in improving on and understanding your craft, so let’s use those extraordinary tools we have 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51bb1268321f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hidden information your README.md can reveal about your team]]></title>
            <link>https://medium.com/@marcneureiter/the-hidden-information-your-readme-md-can-reveal-about-your-team-3c45a9c47d4a?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c45a9c47d4a</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 14:32:56 GMT</pubDate>
            <atom:updated>2026-02-10T14:32:56.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1xmFSUh9y7gNBnML0Lmsw.png" /></figure><p>The readme file of your repo, project or module is more revealing than you think and in more ways than one. And by that I don’t mean the content (or lack thereof), but how it comes to life by many hands: the team members. By how we interact with the readme file we can begin to get a grasp on a “psychogram” of a team. But all that wouldn’t be much of a benefit if there weren’t valuable, actionable steps to take. Bear with me, I’ll get to them in the last section of this article.</p><p>So let’s get started and see: What can a readme file really tell us?</p><h3>How much we care about knowledge transfer</h3><p>I think this is the most obvious point, but also not one that’s very specific to a readme file. There are many other tools for knowledge transfer like company wikis, emails and Slack. Still the presence and content of a readme can tell you how much your team cares about knowledge transfer. For new team members the readme might be the first touchpoint with your documentation.</p><h3>About clarity and clearness</h3><p>In most cases readme files are kicked off just out of habit and filled with details mostly relevant at the time of creation of a repo, project or module. And in many cases it stays like this. In essence what this tells us is: I created this because it’s expected of me, but I don’t really see the value in evolving it. As you grow more senior in your profession you should look out for places like those, as it can denote a bad habit. Following this habit is contagious as it tells your peers: It’s OK to leave it like this, avoid it or make clear decisions about it.</p><p>In this case the readme can tell us how much your team values clear decisions and a clean environment that encourages care about the code base.</p><h3>How we’re able to reach beyond the daily work</h3><p>If you save on documentation, chances are that you put the burden onto somebody else afterwards and manyfold. That sounds obvious, but it still happens. We’re developers, after all, we’re good at writing code, but for writing good documentation and even to <em>know that documentation is needed,</em> a set of very different skills is required, like empathy and being able to obtain a meta-perspective on the process of research, entering a new team and even navigating the social space in and around the team. It can be pretty high-level!</p><p>So the readme can tell us how much you as a team are able to transcend the daily coding practice, take a step back and see what new hires need to get started smoothly.</p><h3>Who is doing what and how often</h3><p>I could have named this chapter “git blame &amp; log” and that’s exactly what I mean literally here. It might be a good idea to try it out once, there’d be a lot to see:</p><ul><li><strong>How<em> frequent</em> are the changes?</strong> This tells us how much love the readme is receiving, but still on a superficial level.</li><li><strong><em>What</em> changes often?</strong> Chapters having good quality, being relevant for the reader and not changing much anymore over time might signal they’re pretty set and mature, so no need to do something there. But if those factors are absent it calls for more clarity about what to do with them.</li><li><strong><em>Who</em> is introducing the changes?</strong> This points us to how distributed the responsibility is. So if a readme file is well-maintained, but only (or mostly) one person is taking care, this might show that the practice is not very well aligned. Could also be this person is well-meaning but not very effective in communicating and spreading good practices (which is OK, we all have strengths and weaknesses). But nonetheless, the person is the single point of failure: when they leave, so does the practice.</li><li><strong><em>Who</em> is introducing changes where?</strong> Now this can be quite interesting as well. While the point above was “communication skills” in general (or the lack thereof), this is more about knowledge transfer. In essence, different people adding and changing stuff all over the place points towards a well-established knowledge transfer. And I think it’s generally agreed upon that it’s a good thing. The “single point of failure” argument applies here as well.</li><li><strong>Is a new team member adding things during onboarding?</strong> And if yes, is it helpful? This can give you hints about a new member’s assertive attitude. But beyond that, if they add a lot that means that a lot was missing, too. Good to know retrospectively.</li><li><strong>Are you removing stuff?</strong> Removing stuff is pretty serious: you actively remove something out of the immediate field of perception (even though it’s still in the git history). If it’s not a stupid move, this points towards somebody being deliberate about reducing complexity and outdated content, improving clarity, or more generally, having made a conscious decision about something.</li></ul><h3>How much we care about alignment</h3><p>As much as it’s true that everyone has their own style of doing things, a very important measure of how mature a team is is its ability to align effectively in the face of increasing complexity. And if a readme file is not supposed to be a place where people can randomly dump stuff in, it can be a place where decisions manifest in the form of clear instructions and guidelines. So indeed, a readme file can potentially give you a picture of how good the alignment level of your team is.</p><h3>Considerations</h3><p>Looking back writing all this I have to admit that the area this topic touches is pretty big. It goes beyond a file, it’s more than about documentation, it even touches team communication and, surprisingly, only very little technical details. I didn’t plan for it to turn out like this, but the interesting thing is that whatever can be learnt here can be applied in a lot of fields like team leadership, communication and alongside professional growth, as well.</p><p>Concluding all that, what takeaways can we drive home now?</p><ul><li><strong>Why the readme file?</strong> Besides code comments, the readme is the most accessible storage space for documentation and obvious point to start with (although this often isn’t reflected in the habits); I’d even go so far that proposals can be handed in in the form of pull requests with changes on the readme file everyone can comment on, where being merged counts as “agreed upon”.</li><li><strong>Representativeness:</strong> use your readme file as source of truth, and if it doesn’t reflect truth, take care of it so it aligns. The more representative the readme is the more value you’ll get out of it. This benefit only surfaces by constant effort.</li><li><strong>Alignment:</strong> by aligning on the basis of written text it becomes easier to avoid misunderstanding. Everyone nodding over some text formulated together is the best indicator that everyone understands the same thing.</li><li><strong>Time saver for discussions:</strong> this effort is well offset over time by being a great reference for your discussions, as well: instead of opening up topics over and over, you can as well link to something that was agreed upon and written down in the readme already. Your memory might not be reliable enough, also your memory is not as convincing as something written down and on top of that, convincing is time-consuming in the first place. So save that time!</li><li><strong>Onboarding and research:</strong> Another time saver resides in the field of onboarding. Be deliberate about the readme and other documentation with your new team members. If they stumble over some problem that could have been solved by better documentation, let them put it there on their own. This creates a great feeling of responsibility that can carry on to daily work. And of course the next one to face this problem won’t have to do the nasty research anymore. Don’t forget to ask new team members what was hard during onboarding and draw your conclusions on how better documentation can help with those problems, in general. Everything else would be a missed chance in getting an outside perspective so you can document stuff that matters most! All that said, it’s not only relevant for onboarding, it’s even extending beyond that every time we research any information we need in order to complete the tasks at hand. So may it be for new hires or other daily research work, the return of investment is recurring!</li><li><strong>Stay flexible:</strong> having something written down is not an argument to beat down new discussions, of course. Discussion is vital and your team should stay approachable towards new ideas and changes. When talking about new ideas, sometimes it can even be helpful to have something written down to start from instead of something that only exists in the heads of the team members.</li><li><strong>Take deliberate action:</strong> When the readme doesn’t fulfil its purpose, be as deliberate with it as you would be with code. Too much complexity? Reduce it! Unnecessary or outdated? Consider removing it or keep it up-to-date. The option “don’t do anything” just spurs confusion.</li><li><strong>Think about the “where”:</strong> Code comments can be considered documentation too, but often they don’t give you a bigger picture, they aren’t really meant for that. So don’t be afraid to move content across comments, readme entries (or eventually company wiki pages) depending on what’s the best place. In general, code comments are most low-level, the readme can be higher level and everything above that usually resides in the company wiki (e.g. system architecture, design or business-related stuff).</li><li><strong>Single source of truth:</strong> The fewer places there are that need updating when something changes, the better. So better maintain a piece of information in only one place, e.g. the readme <em>or</em> the company wiki, but not both. Deep technical specifications — such as component models, logical database designs, or interaction diagrams (UML) — are often better suited for dedicated places. Don’t be afraid to link across comments, readme and wiki pages. Duplication is not a bad thing in code only, but also for documentation.</li><li><strong>Don’t overdo it:</strong> The aim should not be to avoid the need for thinking altogether (for that we have ChatGPT 😉). Documentation creates maintenance cost, so it’s key to strike a good balance.</li></ul><p>I hope this article gave you some interesting food for thought, happy coding and (hopefully not too much) documenting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c45a9c47d4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Suspension Not Detention: Launching Activities Without Callback Headaches]]></title>
            <link>https://medium.com/@marcneureiter/suspension-not-detention-launching-activities-without-callback-headaches-8a1e822a00b7?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a1e822a00b7</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 15:01:17 GMT</pubDate>
            <atom:updated>2025-03-12T15:01:17.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5JwnlXl4QLUNbDzL" /><figcaption>Photo by <a href="https://unsplash.com/@nssaremi?utm_source=medium&amp;utm_medium=referral">nader saremi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>On Android you need to start activities on a regular basis. Those can be system-provided ones or your own. But no matter which, those activities often depend on each other. And to wire everything up you might need to get deep into callback hell. There’s a solution for that: wrapping activity launch code in suspending functions. That dramatically increases readability and maintainability of your code. Let me show you!</p><h3>How it looks</h3><p>In my opinion, business logic in code should be so simple, non-developers can (almost) read it:</p><pre>suspend fun runTakePictureFlow() {<br>    if (!permissionManager.check(CAMERA)) {<br>       if (permissionManager.request(CAMERA) != true) {<br>           appSettingsRunner()<br>       }<br>    }<br><br><br>    if (!permissionManager.check(CAMERA)) {<br>       setMessage(&quot;Couldn&#39;t obtain camera permissions!&quot;)<br>       return<br>    }<br><br><br>    takePictureRunner()<br>        .let(::setPicture)<br><br><br>    setMessage(&quot;Picture was taken!&quot;)<br>}</pre><p>So what this code does is to achieve the following flow:</p><ol><li>Check for camera permissions</li><li>If the check is negative, request camera permissions from the user</li><li>If that still didn’t work, navigate to the app settings so the user can grant the permission manually</li><li>After coming back from the app settings and if the user failed to enable the camera permission, show an error message and cancel the flow</li><li>In all other cases, take a picture and show it</li></ol><p>As you can see this is a suspending function: its flow is asynchronous. permissionManager.request(), appSettingsRunner() and takePictureRunner() are all suspending function calls as well. That means: they return whenever the associated task is finished. Have a look at <a href="https://github.com/marc-neureiter/example-coroutines-modeling/">my GitHub repo</a> to check out the full solution.</p><p>Initially, I wanted to include an example of how complicated that same behavior would be to implement by traditional means, but I feared that would just be too boring. So let me draw your attention to the secret sauce under the hood right away.</p><h3>How it works</h3><p>To be really honest with you, there’s not so much about it. There’s one centerpiece of bringing any API that is based on callbacks into the holy lands of coroutines, and that is suspendCoroutine. In order to start any activity you can ever imagine, use that following simple wrapper:</p><pre>suspend fun &lt;I, O&gt; runActivityForResult(<br>    currentActivity: ComponentActivity,<br>    contract: ActivityResultContract&lt;I, O&gt;,<br>    input: I<br>): O? {<br>    var activityResultLauncher: ActivityResultLauncher&lt;I&gt;? = null<br>    val key = UUID.randomUUID().toString()<br>    suspendCoroutine { continuation -&gt;<br>        activityResultLauncher =<br>            currentActivity.activityResultRegistry.register(key, contract, continuation::resume)<br>                .also { it.launch(input) }<br>    }<br>}</pre><p>This is a simplified version of the final one you can look it up <a href="https://github.com/marc-neureiter/example-coroutines-modeling/blob/main/app/src/main/java/at/marcneureiter/kotlin/coroutines/modeling/lib/runActivity/RunActivityForResult.kt">here</a>. If you want to use it, do so happily, but really refer to the full version that covers some edge cases and has better documentation!</p><p>All this function does is suspending the current coroutine until the activity is finished. In essence, the suspending function only returns when the activity is finished. And this is what enables the fluent, easy to understand code I showed you in the beginning.</p><p>There’s still one piece missing here: how does the implementation of one of such suspending functions look like, for instance permissionManager.request(...)?</p><pre>class PermissionManager(private val activity: ComponentActivity) {<br><br><br>    fun check(permission: String) =<br>          activity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED<br><br><br>    suspend fun request(permission: String): Boolean? =<br>        runActivityForResult(activity, ActivityResultContracts.RequestPermission(), permission)<br>}</pre><p>In the last line of the class you can finally see the call to runActivityForResult and it’s not overwhelming either: wrapping an activity that way is in many cases just a one-liner.</p><h3>View models and Jetpack Compose</h3><p>You can already use runActivityForResult from any activity or fragment, if you want to. But usually, you would like to have the business logic in a view model instead. So how to make runActivityForResult accessible to business logic in the view model?</p><p>I created a nice wrapper for runActivityForResult that can be passed from a view to its view model:</p><pre>class ActivityRunner&lt;I, O&gt;(<br>    private val currentActivity: ComponentActivity,<br>    private val contract: ActivityResultContract&lt;I, O&gt;,<br>) : ActivityRunner&lt;I, O&gt; {<br>    override suspend operator fun invoke(input: I): O? {<br>        return runActivityForResult(currentActivity, contract, input)<br>    }<br>}</pre><p>You can instantiate this class and pass it to any view model like that:</p><pre>val requestPermissionRunner = ActivityRunner(LocalContext.current as ComponentActivity, ActivityResultContracts.RequestPermission())<br><br>LaunchedEffect(Unit) {<br>    viewModel.init(requestPermissionRunner)<br>}</pre><p>Now you can use this runner in the view model like demonstrated in the beginning.</p><p>But to make it even more convenient and to avoid creating an extra instance on each recomposition, you should definitely wrap this in a remember function like this:</p><pre>@Composable<br>fun rememberRequestPermissionRunner(): ActivityRunner&lt;String, Boolean&gt; {<br>    val currentActivity = LocalContext.current as ComponentActivity<br>    return remember { ActivityRunner(currentActivity, ActivityResultContracts.RequestPermission()) }<br>}</pre><p>You can look up the implementation of the other suspending functions <a href="https://github.com/marc-neureiter/example-coroutines-modeling/blob/main/app/src/main/java/at/marcneureiter/kotlin/coroutines/modeling/lib/runActivity/implementation/IndividualActivityRunners.kt">here</a>.</p><h3>Thoughts</h3><ol><li>Note that this only works as long as the calling activity is not destroyed yet. Otherwise there’s really no way we can receive results anymore. Therefore the <a href="https://github.com/marc-neureiter/example-coroutines-modeling/blob/main/app/src/main/java/at/marcneureiter/kotlin/coroutines/modeling/lib/runActivity/RunActivityForResult.kt">full version</a> of runActivityForResult has a check for the activity’s state and changes thereof. Use this function only for waiting for activities to finish or return a result, but not for navigating off to a different activity!</li><li>There’s a best practice to keep view models free from platform-specific types like Intent, ActivityResultContract or ActivityResultLauncher and I recommend you to follow that. You can see an example of mapping between domain and platform code down below.</li><li>You need to write your own wrappers, but all in all you end up with less and easier-to-understand and maintainable code.</li></ol><h3>Further optimization</h3><p>With what I’ve shown here you’re able to model any user flow across activities imaginable and with very simple and malleable code, already.</p><p>There are two iterations of the solution that will be necessary as use cases expand:</p><h3>1. Reduce boilerplate code</h3><p>For each use case you might need to add another runner. That can add up:</p><pre>val pickVisualMediaRunner = rememberPickVisualMediaRunner()<br>val requestPermissionRunner = rememberRequestPermissionRunner()<br>val takePictureRunner = rememberTakePictureRunner()<br>val permissionManager = rememberPermissionManager()<br>val appSettingsRunner = rememberAppSettingsRunner()<br><br>LaunchedEffect(Unit) {<br>    viewModel.init(<br>        pickVisualMediaRunner,<br>        requestPermissionRunner,<br>        takePictureRunner,<br>        permissionManager,<br>        appSettingsRunner<br>    )<br>}</pre><p>That’s a lot of boilerplate code. You can remedy the situation by placing all of those in a single provider for all kinds of runners. You can have a look at the finished solution <a href="https://github.com/marc-neureiter/example-coroutines-modeling/commit/a59f81e20127874dbb1043427b5b423b4a700a4a">here</a>.</p><h3>2. Introduce transform capability</h3><p>Android’s ActivityResultContract already has the capability of transforming input and output data you exchange with other activities. But there’s two problems with that:</p><ol><li>Often the input and output types are platform-bound, and usually we don’t want to have them in business-related code</li><li>If you want to launch your custom or any third-party activities, you might need to write your own ActivityResultContract and you need a custom class that implements a contract for that</li></ol><p>By expanding ActivityRunner‘s capabilities, we can have convenient transformation of input and output data by passing transformation blocks into the constructor, all without the need to create a new contract class:</p><pre>typealias PickVisualMediaRunner = ActivityRunner&lt;PickVisualMediaType, Uri&gt;<br><br>@Composable<br>fun rememberPickVisualMediaRunner(): PickVisualMediaRunner {<br>   val currentActivity = LocalContext.current as ComponentActivity<br>   return remember {<br>       TransformingActivityRunner(<br>           currentActivity = currentActivity,<br>           contract = ActivityResultContracts.PickVisualMedia(),<br>           transformInput = {<br>               val mediaType = when (it) {<br>                   PickVisualMediaType.ALL -&gt; ActivityResultContracts.PickVisualMedia.ImageAndVideo<br>                   PickVisualMediaType.IMAGE -&gt; ActivityResultContracts.PickVisualMedia.ImageOnly<br>                   PickVisualMediaType.VIDEO -&gt; ActivityResultContracts.PickVisualMedia.VideoOnly<br>               }<br>               PickVisualMediaRequest.Builder()<br>                   .setMediaType(mediaType)<br>                   .build()<br>           },<br>           transformOutput = {<br>               // This is just to show the possibility of an exception being thrown. In reality a nullable result would be preferable.<br>               it ?: error(&quot;No image was picked!&quot;)<br>           }<br>       )<br>   }<br>}</pre><p>You can have a look at all implementations <a href="https://github.com/marc-neureiter/example-coroutines-modeling/blob/main/app/src/main/java/at/marcneureiter/kotlin/coroutines/modeling/lib/runActivity/implementation/ActivityRunners.kt">here</a>.</p><p>All in all, by using that approach the platform implementation details are conveniently encapsulated in a reusable way; business logic and implementation details are nicely separated, producing simple, malleable code.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a1e822a00b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Property Drilling: when best practices become best problems in Declarative UI (Compose, Swift UI)]]></title>
            <link>https://medium.com/@marcneureiter/property-drilling-when-best-practices-become-best-problems-in-declarative-ui-compose-swift-ui-86af56dec047?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/86af56dec047</guid>
            <category><![CDATA[declarative-ui]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 13:46:01 GMT</pubDate>
            <atom:updated>2024-11-25T13:46:01.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zY83g5jiOIjcpeGlwz9vdg.png" /></figure><p>Just some time ago I wondered about repeating patterns in the code where in our UI code we just shoveled arguments over arguments from one function to the next. This is called property drilling and is considered a <a href="https://developer.android.com/develop/ui/compose/state-hoisting#property_drilling">best practice for Android</a>. This is no Android and Compose-specific topic though. It also extends to other declarative UI frameworks like SwiftUI. Here, I want to present my take on it and why I disagree with the Android guidelines for a big part.</p><h3><strong>What is property drilling?</strong></h3><p>So to start with, look at that small piece of code:</p><pre>fun Screen(viewModel: ViewModel) {<br>   Text(text = viewModel.title)<br>   Text(text = viewModel.description)<br>   viewModel.entries.forEach { entry -&gt;<br>       Row(onClick = { viewModel.onEntryClick(entry) }) {<br>           Text(text = entry.title)<br>           Text(text = entry.description)<br>           Button(onClick = { viewModel.onDeleteEntryClick(entry) })<br>       }<br>   }<br>}</pre><p>This is indeed very simple. It has only 11 lines in total, while there is a high share of 8 lines that is necessary for the code to function (70%). But we all know it usually doesn’t stay like that. No example in the wild is really that simple. So over time what we usually do is to break this up into smaller pieces to keep the code comprehensible and maintainable. And whooooops, we end up with a lot of code. In a real-world example it could already be near to a monster.</p><pre>fun Screen(<br>   // ⚠️ a lot of parameters<br>   title: String,<br>   description: String,<br>   entries: List&lt;Entry&gt;,<br>   onEntryClick: (Entry) -&gt; Unit,<br>   onDeleteEntry: (Entry) -&gt; Unit<br>) {<br>   Text(title)<br>   Text(description)<br>   EntryList(entries, onEntryClick, onDeleteEntry)<br>}<br><br>fun EntryList(<br>   entries: List&lt;Entry&gt;,<br>   onEntryClick: (Entry) -&gt; Unit,<br>   onDeleteEntry: (Entry) -&gt; Unit<br>) {<br>   entries.forEach { entry -&gt;<br>       EntryView(<br>           title = entry.title,<br>           description = entry.description,<br>           onClick = { onEntryClick(entry) },<br>           onDeleteClick = { onDeleteEntry(entry) })<br>   }<br>}<br><br>fun EntryView(<br>   // ⚠️ a lot of parameters<br>   title: String,<br>   description: String,<br>   onClick: () -&gt; Unit,<br>   onDeleteClick: () -&gt; Unit<br>) {<br>   Row(onClick = onClick) {<br>       Text(title)<br>       Text(description)<br>       Button(onClick = onDeleteClick)<br>   }<br>}</pre><p>Property drilling <a href="https://developer.android.com/develop/ui/compose/state-hoisting#property_drilling">is said</a> to improve reusability and understandability as well as to mitigate performance issues in Compose. Let’s get into that later, but in the meantime we can see this code has already 54 lines in total: 22 lines of argument passing and parameter declaration, and still only 8 lines of code that are essential to get the same job done. The share of the “essential” lines plummets to 14%. Of course you can’t just reduce an architectural discussion to this number but we still have to consider: the more and deeper we want to nest our UI code, the more this trend continues. So, property drilling has the capacity to penalize understandable and clean code in some way. Thus, it’s better to know where to use it and where not — which is exactly the matter of this article.</p><p>So let’s jump into an alternative to that! Afterwards I’ll discuss the pros and cons of those competing approaches and where I think the alternative approach should be picked. My intention for you is that working on your declarative UI code with this approach will be way more fun and effective in future!</p><h3><strong>Alternative approach</strong></h3><pre>class ViewModel {<br>   val state = State(<br>       title = &quot;We have 10 entries here&quot;,<br>       description = &quot;Click one of those 10, please!&quot;,<br>       entries = List(10) { Entry(&quot;Title $it&quot;, &quot;Description $it&quot;) }<br>   )<br><br>   fun dispatch(action: Action) {<br>       when (action) {<br>           is Action.EntryClick -&gt; Unit // some logic goes here<br>           is Action.EntryDeleteClick -&gt; Unit // some logic goes here<br>       }<br>   }<br><br>   data class State(<br>       val title: String,<br>       val description: String,<br>       val entries: List&lt;Entry&gt;,<br>   )<br><br>   sealed interface Action {<br>       data class EntryClick(val entry: Entry) : Action<br>       data class EntryDeleteClick(val entry: Entry) : Action<br>   }<br>}<br><br>fun Screen(viewModel: ViewModel) {<br>   Screen(viewModel.state, viewModel::dispatch)<br>}<br><br>fun Screen(state: State, onAction: (Action) -&gt; Unit) {<br>   Text(state.title)<br>   Text(state.description)<br>   state.entries.forEach { entry -&gt;<br>       Row(onClick = { onAction(Action.EntryClick(entry)) }) {<br>           Text(entry.title)<br>           Text(entry.description)<br>           Button(onClick = { onAction(Action.EntryDeleteClick(entry)) })<br>       }<br>   }<br>}</pre><p>What you see here is an MVI (model-view-intent) approach where the view model communicates state data structures to the view and the view communicates intents (or actions for the sake of the example) back to the view model.</p><h4><strong>Working with the alternative approach</strong></h4><p>There are indeed arguments against this alternative approach. But I don’t want to judge each approach individually but rather comparatively.</p><p>To show how easy it is to work with this approach let’s start with the original minimal code example and refactor it into the new approach, and for that we start with extracting the forEach part into a function EntryList:</p><pre>fun Screen(state: State, onAction: (Action) -&gt; Unit) {<br>   Text(state.title)<br>   Text(state.description)<br>   EntryList(state, onAction)<br>}<br><br>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   state.entries.forEach { entry -&gt;<br>       Row(onClick = { onAction(Action.EntryClick(entry)) }) {<br>           Text(entry.title)<br>           Text(entry.description)<br>           Button(onClick = { onAction(Action.EntryDeleteClick(entry)) })<br>       }<br>   }<br>}</pre><p>This took me 10 seconds by using IntelliJ’s function extraction refactoring feature (select the code, hit the shortcut, enter the name of the new function, in this case EntryList).</p><p>Now let’s do the same to extract the EntryView out of the list:</p><pre>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   state.entries.forEach { EntryView(it, onAction) }<br>}<br><br>fun EntryView(entry: Entry, onAction: (Action) -&gt; Unit) {<br>   Row(onClick = { onAction(Action.EntryClick(entry)) }) {<br>       Text(entry.title)<br>       Text(entry.description)<br>       Button(onClick = { onAction(Action.EntryDeleteClick(entry)) })<br>   }<br>}</pre><p>This took me another 10 seconds.</p><p>What about if we want to move the “description” part of the UI from the Screen to the EntryList? Let’s just move that line</p><pre>Text(state.description)</pre><p>Into EntryList:</p><pre>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   Text(state.description)<br>   state.entries.forEach { EntryView(it, onAction) }<br>}</pre><p>As you might have noticed, the line is identical: you have the same state in the EntryList as in Screen so you can just access it as before. So this took me only a few seconds as well. Also the communication in the direction of the view model is equally flexible: you can call onAction from basically everywhere.</p><p>Let’s look at the final version:</p><pre>fun Screen(viewModel: ViewModel) {<br>   Screen(viewModel.state, viewModel::dispatch)<br>}<br><br>fun Screen(state: State, onAction: (Action) -&gt; Unit) {<br>   Text(state.title)<br>   EntryList(state, onAction)<br>}<br><br>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   Text(state.description)<br>   state.entries.forEach { EntryView(it, onAction) }<br>}<br><br>fun EntryView(entry: Entry, onAction: (Action) -&gt; Unit) {<br>   Row(onClick = { onAction(Action.EntryClick(entry)) }) {<br>       Text(entry.title)<br>       Text(entry.description)<br>       Button(onClick = { onAction(Action.EntryDeleteClick(entry)) })<br>   }<br>}</pre><p>It has the same number of functions as its property drilling competitor, but only 20 instead of 54 lines of code, while the number of essential lines to get the job done remains almost unchanged at 10, which makes for a 50% share of the total lines of code. Additionally, the readability is significantly better and as you have seen by example, that code is extremely malleable as there’s no need to change the function signatures when you change responsibilities of a function. By making the function signatures very rigid, the code inside can change much easier.</p><h3><strong>Arguments</strong></h3><p>Now it’s time to review the pros and cons. Let’s jump into the arguments one-by-one. In short, those are the thoughts that bubble up frequently when discussing this approach:</p><ol><li>“This increases coupling”</li><li>“You can’t reuse that”</li><li>“It’s harder to understand”</li><li>“It’s less performant”</li></ol><h4><strong>“This increases coupling”</strong></h4><p>This conception arises a lot when using that approach. But it’s based on a wrong assumption that coupling is “that you need to know something”. Indeed, most parts of the view need to know State, Entry and Action. There are some cases where you don’t want that and we’ll discuss it later.</p><p>We don’t have time here to go down the rabbit hole about the term “coupling” but, in simplified terms, if you want to measure coupling you should instead ask “how many places do I need to change if I add/modify/remove a certain feature?”.</p><p>For example, let’s remove the “description” from the screen. In the property drilling example you’d need to remove those lines of code:</p><pre>val description: String<br>description = viewModel.description<br>description: String<br>Text(description)</pre><p>And the more the design evolves and the deeper the hierarchy goes, the more you have to drill into it, forcing you to read, understand and finally touch more and more layers of the UI. In contrast, in the alternative approach you’d only need to remove those lines instead:</p><pre>val description: String<br>Text(state.description)</pre><p>It is simplified but still right to say: the coupling of the latter example is considerably less. You’ll feel the difference the more the UI evolves over time.</p><p>This of course, comes at a cost: the signatures and calls of the view functions are now indeed very strongly coupled to the data structures:</p><pre>fun Screen(state: State, onAction: (Action) -&gt; Unit)<br>fun EntryList(state: State, onAction: (Action) -&gt; Unit)<br>fun EntryView(entry: Entry, onAction: (Action) -&gt; Unit)</pre><p>So this introduces a comparatively hard-to-change contract between the view model and the views between the views. But this is the kind of coupling we even want to have for this example; we could even call it “good coupling”: if you delete something the implementation breaks only at the place where it’s really used instead of all over the UI code. This of course also applies to other changes like additions and modifications.</p><h4><strong>“You can’t reuse that”</strong></h4><p>This is undoubtedly true. Consider, we have two modules A and B, both having an EntryA and EntryB, the proposed approach doesn’t work anymore as soon as you want to reuse the view.</p><p>As</p><pre>fun EntryView(entry: Entry, onAction: (Action) -&gt; Unit)</pre><p>is not compatible with EntryA and EntryB you would be better off with a signature like</p><pre>fun EntryView(<br>   title: String,<br>   description: String,<br>   onClick: () -&gt; Unit,<br>   onDeleteClick: () -&gt; Unit<br>)</pre><p>because it can instantly be used with EntryA as well as EntryB:</p><pre>EntryView(entryA.title, entryA.description, ...)</pre><p>But in how many cases are you really going to need that? The answers differ. In many, if not most cases, you don’t know beforehand. Overdoing reusability can be a sign of susceptibility to the <a href="https://wiki.c2.com/?PrematureOptimization">premature optimization</a> or <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a> fallacy. So if you design for reusability, think twice whether you’re really going to reuse it. Reusability comes with a cost, that is usually lower understandability, changeability and maintainability due to unnecessary complexity, indirection and artificial decoupling.</p><h4><strong>“It’s harder to understand”</strong></h4><p>I think it’s very important that the solutions are not more complex than needed and comparatively easy to reason about.</p><p>One can separate the thoughts about understandability into three parts:</p><p><strong>Learning curve</strong></p><p>You need to get accustomed to new approaches and patterns (in this case the MVI architecture). So initially, it takes some time to get into this way of views and view models communicating with each other. Thus, first: yes, it has a learning curve. But so does any new concept.</p><p><strong>Coupling to data that is not needed</strong></p><p>Secondly, when you just pass the same data structures all the time, not all of that data contained is used in all places. For example:</p><pre>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   state.entries.forEach { EntryView(it, onAction) }<br>}</pre><p>This function only uses entries and forgets about the rest. This is indeed an anti-pattern in some cases (and we’ll get to that below). But what you get in return is high flexibility. Remember? You can just move a line from another function</p><pre>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   Text(state.description)<br>   state.entries.forEach { EntryView(it, onAction) }<br>}</pre><p>and you’re done: it still works. This approach costs you little and gives you a lot of flexibility in return.</p><p>So why do we learn this is an anti-pattern? Because it is an anti-pattern for core, reusable API. Imagine a REST API you have to give arguments that it doesn’t even need: it’s an impossible thought! But in a self-sufficient module or package, handing over bigger data structures in that fashion is not a sin and should be decided upon individually.</p><p><strong>Looking up where the data comes from</strong></p><p>Passing data structures down the view hierarchy seems counterintuitive to the ones not yet accustomed to the approach. This is understandable. But in my experience this is a matter of getting used to.</p><p>For example, let’s draw the graph how the data flows from function to function:</p><pre>ViewModel → Screen → EntryList → EntryView</pre><p>In order to understand how the data in EntryView is wired up with the ViewModel you need to navigate through the whole graph backwards. You can never know how data fed into one function is mapped to the next, also naming is not always consistent, so you often have to read through and understand all levels of the hierarchy wherever the data is passed further.</p><p>So in contrast, in that function from above</p><pre>fun EntryList(state: State, onAction: (Action) -&gt; Unit) {<br>   state.entries.forEach { EntryView(it, onAction) }<br>}</pre><p>you can either just command/control-click entries in your IDE and you will end up in the ViewModel where the data originates from or can look up the places where entries is changed in the view model. By jumping that far of course you lose what happens in between. This can be obscuring in some cases, but in most cases we know what the State‘s and ViewModel‘s jobs are and mostly the data is simply mapped 1-on-1 onto the view anyway. So, if it’s not obvious where the data comes from, it might most probably be because of a faulty implementation of the MVVM or MVI architecture and not the architecture itself.</p><p>When judging the comprehensiveness of a technical solution you always need to be fair. Is a function with 10 parameters still comprehensible? Is passing arguments from function to function 4 levels deep comprehensible? I think this can and should be decided on a per-case basis.</p><h4><strong>“It’s less performant”</strong></h4><p>This can indeed be a problem. When speaking of Compose, passing data structures can become a problem in this regard. For each instance where data is passed to another composable function, the runtime needs to compare the whole data structure. If the data is equal then we’re fine: no recomposition needed. And if the data structure can not be compared, the runtime always triggers a recomposition which can be CPU-intensive and potentially lead to less responsive UI.</p><p>But immutable data classes can be compared. And if the data didn’t change, there’ll be no recomposition.</p><p>So why are we then concerned with performance issues in Compose? Because data structures are more expensive to allocate, compare and garbage-collect. So you should definitely not use the MVI approach for data that is either very, very big or updates very often. Let’s consider three scenarios here:</p><ol><li><strong>Scenario 1:</strong> the state updates when data is loaded, the user performs a keystroke or clicks an UI element. In this scenario, an update can happen up to a few times per second at max for some short period of time. In this case we don’t need to be concerned with performance, battery life or similar.</li><li><strong>Scenario 2:</strong> the state updates very often, more than a few times per second, so for example while the UI is scrolling. Animations like those might need a refresh rate of 30 or more per second and we definitely need to be concerned with performance and memory management overhead; even battery life might be an issue in case of an ongoing animation.</li><li><strong>Scenario 3:</strong> the data structure is very big. In this case the UI state data structure is not the right place to contain that data and you should most probably use paging or a similar approach instead.</li></ol><p>My suggestion is to not optimize for performance if your app runs smoothly on the expected range of target devices and for the specific use case (see <a href="https://wiki.c2.com/?PrematureOptimization">premature optimization fallacy</a>). Instead, in most usual cases you should be free to focus on optimizing for maintainability, simplicity and changeability.</p><h3><strong>Conclusion</strong></h3><p>Which approach to use heavily relies on your use case. So here are some key takeaways:</p><ol><li>Keep the <a href="https://wiki.c2.com/?PrematureOptimization">premature optimization</a> and <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a> fallacies in your mind and try to find simple solutions to optimize for understandability, maintainability and changeability first</li><li>If you need to optimize for performance or you have a heavy-duty UI that can easily drain the battery, separate simple data that changes fast from more complex data that changes slowly</li><li>Only optimize for reusability what you know will become reused (because even then it might not always pay as the future solution might demand things you couldn’t anticipate)</li><li>Give the MVI approach a shot for a real-world, frequently changed, complex and nested UI to get accustomed to it and to see where it fits for your use case</li><li>Don’t trust guidelines blindly, even from Google 😉</li></ol><p>I hope this will help you to pick the right tools for the challenges ahead. Have a great time coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86af56dec047" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The struggle with breaking tests and hard to change code: Test API to the rescue!]]></title>
            <link>https://medium.com/@marcneureiter/the-struggle-with-breaking-tests-and-hard-to-change-code-test-api-to-the-rescue-ada2930e8684?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ada2930e8684</guid>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 09:34:42 GMT</pubDate>
            <atom:updated>2024-03-21T09:34:42.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tClkbd0uSu8VtigQfTrRCw.jpeg" /><figcaption><a href="https://unsplash.com/de/@carrie_borden">Carrie Borden</a> and <a href="https://unsplash.com/de/@markusspiske">Markus Spiske</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p><strong>TL;DR:</strong></p><ul><li><strong>Putting tests on production code can make it very hard to work with the code</strong>: the tests can be difficult to understand and the production code can become more challenging to change because you have to fix tests alongside — it’s bad for a variety of reasons.</li><li><strong>Create a test API:</strong> by comparatively small effort you can create a test API that abstracts away technical implementation details so your tests are easier to understand and change. As the coupling between the test and production code becomes less, you’ll notice that production code becomes way easier to change.</li><li><strong>This is a boost for your and your team’s efficiency and developer experience!</strong></li><li>Coding <a href="#example">example</a> and explanatory <a href="https://youtu.be/JWKHY9LEgRM">video</a> included!</li></ul><h3><strong>Omg the code is so hard to change!</strong></h3><blockquote>„If the structure of the tests follows the structure of the production code, then the tests are inextricably coupled to the production code”<br>– Uncle Bob</blockquote><p>As software developers, we naturally take our work seriously, and this includes adding tests with our production code from the very start. However, as we delve deeper into writing test code, meticulously covering every conceivable test case, you may have noticed that not all tests are created equal. Over the years, it feels like some tests become so intertwined with our production code that working with them is like wading through molasses. Weren’t we told that tests are supposed to boost our efficiency overall?</p><p>That’s true. Tests should be fast to read, write and modify — same as our production code. The problem lies within the depths of the code’s architecture, as is very often the case when development speed and experience suffer. So let’s examine!</p><h3><strong>Why, oh why?</strong></h3><p>Architecturally speaking, tests sit on top of our production code. They are independently deployed, but they depend on our production code. And whenever we change something in production code it’s not necessarily the changing part that causes the biggest problem but the stuff that depends on it (in this case: the tests), as it doesn’t work with the new behavior or structure. I’m sure you have experienced that a ton of times.</p><p>Consequently, you need to fix your tests so they work with your production code again. This is very bad as tests can only serve their purpose if they are as stable as possible. If you want them to protect you against mistakes in the production code, you surely don’t want to introduce another source of mistakes by having to rewrite big parts of your test code. So the goal must be to keep them as stable as possible.</p><p>Something <strong>stable</strong> (tests) depending on something <strong>volatile</strong> (much of the production code) is a basic problem in software architecture. And usually you use abstraction or dependency inversion to solve those. In this case we can go with abstraction: a test API.</p><p>Don’t back off here thinking “why should I create a dedicated API and a layer of complexity only for testing?”. I’d say, only if it decreases overall complexity perceived during ongoing development of your system. We are using architectural means for solving challenges all day. It’s just a matter of getting used to it. I still remember the times when the MVVM pattern felt like a waste of time for me. That was, back then, because I hadn’t spent so much time <em>maintaining</em> UIs yet. Now, I know that mashing multiple concerns into one class makes me only faster up-front. It sounds silly now, but I know we’ve all been there some way or the other.</p><p>Saying that introducing a test API grants you superpowers might be an overstatement, but if you are trying to implement a new feature and struggling with tests a third of the time: give it a try! By utilizing it in the right way you’ll be able to notice that revamping a whole production class can be a thing that doesn’t need a rewrite of your tests anymore: on the contrary, the tests still secure the production code from regressions while you are carving out responsibilities into various new classes and methods and move code around between them, essentially giving you strong confidence in your implementation throughout the process. But let’s come back to examining the impact of this approach in more detail after the example below so it becomes less words and more tangible results.</p><h3><strong>Introducing: test API — an example</strong></h3><p>In order to make the topic as easy as possible to understand I prepared a <a href="https://youtu.be/JWKHY9LEgRM">video here</a> and don’t forget to continue with the <a href="#conclusion">conclusion</a> below. So feel free to follow that one through, or in case you have no audio, below there is a summary for you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJWKHY9LEgRM&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJWKHY9LEgRM&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FJWKHY9LEgRM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eee37b235a60d95e9ae8639d6f833803/href">https://medium.com/media/eee37b235a60d95e9ae8639d6f833803/href</a></iframe><p>Let’s say we have that little piece of production code:</p><pre>class UserViewModel(<br>    private val userRepository: UserRepository,<br>    private val sessionManager: SessionManager,<br>    private val dateProvider: DateProvider,<br>) {<br>   var viewData: ViewUserData = ViewUserData.EMPTY<br>   var errorMessage: String? = null<br>   var isLoading: Boolean = false<br>}</pre><p>It takes some dependencies in the constructor and exposes its state through three properties. The first part of A test of this class might look like this:</p><pre>class UserViewTest {<br>    private val mockHttp = MockHttp()<br>    private val userService = mockHttp.getUserService()<br>    private val userRepository = UserRepository(userService)<br>    private val sessionManager = SessionManager()<br>    private val dateProvider = DateProvider { LocalDate.parse(&quot;2024-02-21&quot;) }<br><br>    private val testUser = User(<br>        id = &quot;123123&quot;,<br>        name = &quot;Marc&quot;,<br>        birthday = LocalDate.parse(&quot;1986-10-12&quot;)<br>    )<br><br>    ...</pre><p>So to make the test work, the view model will need a mock HTTP service that is able to receive some user data via the userService. That one is used by a repository. And that repository alongside the sessionManager will thereafter be used by the view model.</p><p>Let’s continue:</p><pre>@Test<br>fun `Simple success case`() {<br>    mockHttp.mock(&quot;getUser&quot;) { testUser } // (1) initialize the mock behavior<br>    sessionManager.logIn(testUser.id) // (1) set the session state<br><br>    ...<br><br>    val sut = UserViewModel( // (2) instantiation of the production class <br>        userRepository,<br>        sessionManager,<br>        dateProvider<br>    )<br><br>    assertEquals( // (3) assertion<br>        UserViewModel.ViewUserData(&quot;Marc&quot;, &quot;37 years&quot;),<br>        sut.viewData<br>    )<br><br>    ...<br>}</pre><p>So here I am (1) setting some preconditions, (2) instantiating the view model with all its dependencies above and (3) checking whether the correct user data is put out.</p><p>So, what should we do if we were to introduce a test API? Let’s extract those calls in the test function into smaller function pieces:</p><pre>@Test<br>fun `Simple success case`() {<br>   givenUser(testUser) // (1)<br>   givenLoggedIn(testUser) // (1)<br><br>   ...<br><br>   whenInitializing() // (2)<br><br>   thenDataIsDisplayed( // (3)<br>       name = &quot;Marc&quot;,<br>       age = &quot;37 years&quot;<br>   )<br>}</pre><p>That’s not only easier in our eyes, it also conveniently abstracts the implementation details from the business of the test. Speaking of technical implementation:</p><pre>private fun givenUser(testUser: User = testUser) {<br>    mockHttp.mock(&quot;getUser&quot;) { testUser }<br>}<br><br>private fun givenLoggedIn(testUser: User = testUser) {<br>    sessionManager.logIn(testUser.id)<br>}<br><br>private fun thenDataIsDisplayed(name: String, age: String) {<br>    assertEquals(<br>        UserViewModel.ViewUserData(name, age),<br>        sut.viewData<br>    )<br>}</pre><p>As you see, I added parameters to all of the functions above. So whenever we want to test with different users we might simply pass different user instances to givenUser, even changing it during runtime. And to verify different view states we can pass varying data to thenDataIsDisplayed accordingly.</p><pre>private fun whenInitialized() {<br>   sut = UserViewModel( // sut becomes class member!<br>       userRepository,<br>       sessionManager,<br>       dateProvider,<br>       dispatcherProvider<br>   )<br>}</pre><p>This function prefixed by “when” is the place where we finally interact with the production class. But it could be any other subsequent interaction as well, like calling a function to simulate a click on the user interface.</p><p>The use of functions, parameter names and arguments like this serves the purpose of readability and reusability pretty effectively. Let’s showcase that in another test case:</p><pre>@Test<br>fun `Is first loading and empty, then done loading and data is present`() {<br><br>    ...<br><br>    whenInitializing()<br><br>    runCurrent()<br><br>    thenIsLoading()<br><br>    thenDataIsDisplayed( // empty stare first<br>        name = &quot;&quot;,<br>        age = &quot;&quot;<br>    )<br><br>    advanceTimeBy(processingTime + 1)<br><br>    thenIsNotLoading() // finished loading<br><br>    thenDataIsDisplayed( // filled state<br>        name = &quot;Marc&quot;,<br>        age = &quot;37 years&quot;<br>    )<br><br>    ...<br>}</pre><p>So we reused most of the functions created above; we only needed to introduce two extra functions to accommodate the loading state (thenIsLoading(), thenIsNotLoading()).</p><p>That’s already nice, but the true powers of the test API over time can only be revealed if we <strong>do changes</strong> as we would expect throughout the development of a project and with the <strong>scale</strong> of our test class.</p><p>What if we decide that testing the view model with all its adjacent dependencies in place is too complex and we want to get rid of mockHttp? That would break our original test in many places — in each and every test case or function:</p><pre>mockHttp.mock(&quot;getUser&quot;) { testUser } // &lt;-- it breaks here</pre><p>Or let’s consider changing the way the production class communicates through its API and encapsulate the three properties in a single state data structure:</p><pre>// Before:<br>var viewData: ViewUserData = ViewUserData.EMPTY<br>var errorMessage: String? = null<br>var isLoading: Boolean = false<br><br>// After:<br>var state = State() // &lt;-- single state property<br>data class State(<br>    var viewData: ViewUserData = ViewUserData.EMPTY,<br>    var errorMessage: String? = null,<br>    var isLoading: Boolean = false,<br>)</pre><p>This is a very common transition if we’re coping with increasing complexity. Here again test code breaks at many places:</p><pre>assertEquals(<br>   UserViewModel.ViewUserData(name, age),<br>   sut.viewData // &lt;-- is breaks here<br>)</pre><p>We would need to go through all of those test cases where the original state is mentioned, try to understand them and fix the broken calls one-by-one. But with a test API in place, we reduce those places to only the code behind the test API. It might seem negligible in this example, but just imagine three times the dependencies, ten times the test cases or a multitude of times the complexity. It scales fast!</p><p>If you want to check out the example project and its progression steps in whole, feel free to have a look at <a href="https://github.com/eder7/example-testing">that GitHub project</a>, alongside the <a href="https://github.com/eder7/example-testing/commits/main/">commit history</a> as well as the <a href="https://github.com/eder7/example-testing/blob/main/testing-api/src/main/java/com/example/testingApi/UserViewModel.kt">production</a> and <a href="https://github.com/eder7/example-testing/blob/main/testing-api/src/test/java/com/example/testingApi/UserViewTest.kt">test code</a>. I designed it with minimal library dependencies and with naive implementation so you don’t really need to know the Kotlin programming language or ecosystem in detail at all.</p><p><strong>Conclusion</strong></p><p>What you’ve seen in this code example was one way to implement a test API. It follows the very common <a href="https://martinfowler.com/bliki/GivenWhenThen.html"><strong>Given-When-Then</strong></a> structure (another variant of this is <a href="https://xp123.com/3a-arrange-act-assert/"><strong>AAA = Arrange-Act-Assert</strong></a>). Note that test APIs can exist <strong>on all levels</strong>, so not primarily only on unit level but also up to UI or system tests (also see <a href="https://martinfowler.com/bliki/PageObject.html">Page Object</a>). And putting the test API right in the test class where it acts on production code is only one way to do it. In fact, it’s only the simplest.</p><p>To progress the design even further you may also consider moving the test API into a <strong>dedicated class</strong> that you can instantiate in your test class (composition) or into a <strong>base class</strong> of your test class (inheritance), but consider composition over inheritance! So the simple approach is fine for most cases, but if you’re interested in the composition approach, feel free to have a look at <a href="https://medium.com/monsterculture/sweetest-intro-5551e785f2ab">that other blog article of mine</a>.</p><p>Let’s recap once again what this approach gives us:</p><ol><li><strong>Comprehensibility:</strong> we might have added complexity to the test code structure, but it is easier to understand; the test case is broken down into a comprehensible picture of business-facing functionality; each function makes the meaning, expectation and variation of its technical implementation clear through its name and parameter list.</li><li><strong>Separation of concerns:</strong> test cases mainly tackle the <em>what</em> of the tests (the <em>business</em>), the code behind the test API is concerned with the <em>how</em> (technical implementation details). If the <em>behavior</em> of the system changes, usually only the business part in the test cases need to be changed and if the <em>technical implementation details</em> change, only the code behind the test API needs to be changed.</li><li><strong>Maintainability:</strong> the test code might be a bit harder to write once, but the production code (including the test code) becomes way easier to change for the next at least ten times ahead.</li></ol><p>It turns out that even usually very hard heavy lifting in the code like changing dependencies or the API of the production code doesn’t really need to be held up by complicated broken test code. On the contrary: the tests in place can still survive and be stable in big parts to accompany the refactoring process, giving us confidence we haven’t broken the production code.</p><p>As always with good architectural choices, the implementation might be harder up-front, but the more we progress through time, modify and grow our project, the more the approach pays off. By going that route, instead of making code unnecessarily hard to change, we can even <em>incentivize</em> ongoing evolution (because, as you know, change is the only constant).</p><p>But nonetheless, this is no recipe to be followed blindly (as always): I think trying it out, giving it a chance and seeing how hard or easy it is to introduce changes over time is the best way to get a grasp of where and when it’s most useful to be put in place.</p><p>I hope you have a lot of fun trying out that approach altogether with your IDE’s refactoring tools — see you another time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ada2930e8684" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[sweetest — create tests you actually love working with]]></title>
            <link>https://medium.com/monsterculture/sweetest-intro-5551e785f2ab?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5551e785f2ab</guid>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 13:23:52 GMT</pubDate>
            <atom:updated>2018-10-09T13:23:52.301Z</atom:updated>
            <content:encoded><![CDATA[<h3>sweetest — create tests you actually love working with</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFsSnmMVDBm3DmNYegVp5Q.png" /></figure><p>You put a lot of love into what you do, and that is especially true for your production code. Why is it then, that test code is usually so ugly? The good news is that there are solutions, and you can apply them right away in your test code — and also a new framework which could help you a lot to eliminate annoying setup and mocking code.</p><h3>In a nutshell</h3><p><a href="http://github.com/mysugr/sweetest">sweetest</a> is a lightweight <strong>framework</strong> for managing the increased complexity that comes with having <strong>integration tests on top of unit tests</strong> or when you have a large number of <strong>dependencies</strong>. As writing tests isn’t everyone’s favourite task, it is no wonder that test code often look awful. <a href="http://github.com/mysugr/sweetest">sweetest</a> is here to change that, sparking discussion about architecture and design of test code and facilitating automated tests in <strong>Kotlin</strong> which you actually like working on.</p><h3>So what’s the problem?</h3><p>At mySugr we had quite a journey when we tried to find out how to approach test automation (read more about that in the <a href="https://engineering.mysugr.com/a-journey-to-better-test-automation-9c33821c52fc">last blog post</a>, it provides great and important background you should definitely know about). In fact it turned out to be quite hard: we had a look at the <a href="https://martinfowler.com/articles/practical-test-pyramid.html">testing pyramid</a> and as a result we saw the need to come up with more <a href="https://martinfowler.com/bliki/IntegrationTest.html">integration tests</a>. Unfortunately, adding integration tests bloated our automated test suite with messy and often duplicated test code.</p><p>The question is, how we can we get rid of ugly, unreadable test code and produce tests we actually like working with?</p><h3>The mess explained</h3><p>To have a clearer picture about where we’re coming from, let me show you a simple software stack that we’re trying to test. It consists of a LoginViewModel that handles the presentation behaviour on top of an AuthManager which contains the business logic of a user login feature. Here’s how we put tests on them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*GchF_5vV6O45tV1l" /><figcaption>Tests put on a simple architecture</figcaption></figure><p>We have to mock all needed dependencies in order to isolate the unit under test. E.g. for the LoginViewModelTest we mock AuthManager. For AuthManagerTest we have to supply a BackendGateway mock as a dependency. In this example we also want to know whether the units integrate well, so we introduce an integration test.</p><p>A lot of stuff is needed to make it work. We have to set up mocks, supply them to the constructor of some class under test, interact with the class under test and then assert results and states. Also the interactions with the units with the mocks are asserted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*mBZmcbe7tZasL2ep" /><figcaption>Complexity of having an integration test on top of unit tests</figcaption></figure><p>As one can see, we have the problem of code duplication: e.g. the assertion logic of the AuthManagerTest as well as the mocking code can be shared with the LoginIntegrationTest. Also the setup of LoginViewModel can be found once in its unit test <em>and</em> in the integration test. When you transfer that simple example to larger classes with much more dependencies (which is totally realistic), it can become a huge pain to add an integration test on top of already existing unit tests — it’s just a lot of duplicated work and maintenance can become hell. It seems to be accepted as being a painful thing as well as something necessary, but definitely up to improvement.</p><p>Before I show you our solution to that mess, let me show you a real life example of how this testing hell looked like at mySugr:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb1c6bda0b256a68db8fedec437b6208/href">https://medium.com/media/cb1c6bda0b256a68db8fedec437b6208/href</a></iframe><p>The example above shows a typical declaration of properties which are used later on. Nothing special to notice here, except that there are a lot. But now let’s look at the setup function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e712a3b43dccbb06e9a2ca155ea107c/href">https://medium.com/media/8e712a3b43dccbb06e9a2ca155ea107c/href</a></iframe><p>As you can see in the example above, all properties have to be initialized with mocks or the objects under test; a lot of stubbing is going on to define the mock’s behaviour. That is just one integration test. If you imagine that we put all of the dependencies under unit test you can see how painful all that duplication can really become.</p><h3>How can we escape this test code hell?</h3><p>It’s simple: we can apply principles of clean code to test code too. This way we end up with code that is much more maintainable, and also more readable. In our opinion test code should:</p><ul><li>document the behaviour of the system under test</li><li>be easy to read and self-explaining</li><li>be well-factored like production code and</li><li>be reusable</li></ul><p>For us, the ingredients for reaching these goals is the use of abstraction and some Kotlin DSL magic plus a brand-new testing framework that puts it all together. That framework is called “<a href="http://github.com/mysugr/sweetest">sweetest</a>” and its aim is to sweeten up your test code so you don’t have to repeat yourself anymore and to make test setup work so easy that you can play with scenarios and edge cases much more freely.</p><h3>How does it look?</h3><p>Let me show a simple example of test code in <a href="http://github.com/mysugr/sweetest">sweetest</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32cabc443e170b501cd655630afddf79/href">https://medium.com/media/32cabc443e170b501cd655630afddf79/href</a></iframe><p>Looks good, doesn’t it? So let’s explore what the main ingredients of this framework are…</p><h3>Abstraction</h3><p>The technical complexity of the test isn’t visible at the test level anymore as the implementation is abstracted away. We don’t even have to deal with test data here: in the example we’ve just used user.givenEnteredPasswordIsIncorrect() to set a wrong password in memory. In my opinion it’s good practice to see the test data setup as a matter of parameterisation. This way it’s easier to reuse and mutate scenarios to come up with new edge cases. This is of course just a very simple example, but it becomes more interesting for more complex test parameters and scenarios.</p><p>Implementing a test as seen above requires all the technical implementation of the test to be abstracted to a dedicated class. We call these classes “step definitions classes” or simply “steps classes” (as it’s also usual for <a href="https://cucumber.io/">Cucumber</a>) and create one of these per class under test, e.g. AuthManagerSteps. All the setup, mocking, interaction and assertion code goes there; and for this simplified example it would actually look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa7c89fb4cb327abf5d143eefe7f15d/href">https://medium.com/media/4fa7c89fb4cb327abf5d143eefe7f15d/href</a></iframe><p>In this example we follow the given-when-then pattern, where functions containing setup or setting preconditions begin with given, interactions begin with when and assertions with then. That way one can easily tell them apart when editing or when auto-completion is used in the IDE.</p><h3>Dependencies</h3><p>When we write apps in a modular way we usually end up with lots of classes being dependent on each other. There are ways to deal with a large number of dependencies like dependency injection, but on the test side we also have to deal with this complexity. Nonetheless you won’t find much setup code for creating all these dependencies in a test written with <a href="http://github.com/mysugr/sweetest">sweetest</a>. The reason for that is that our framework manages dependencies totally in the background. And it doesn’t interfere with the dependency injection framework you use in your production code.</p><p>Most dependency handling is a matter of configuration in <a href="http://github.com/mysugr/sweetest">sweetest</a>. Regarding the example above: when you want to tell the framework that AuthManager is under test, you just call requireReal&lt;AuthManager&gt;() on the test configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/209c126daab5bc716f48e9c256ecf75a/href">https://medium.com/media/209c126daab5bc716f48e9c256ecf75a/href</a></iframe><p>Then you get a real instance of AuthManager and all its dependencies are automatically mocked and supplied to the constructor. The simple message: you don’t have to set up or hand over any objects anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*_-ESOXmFfGMYDkuH" /></figure><p>If you’d like to create an integration test you would just have to add another requireReal statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94c56998d354bfed1db772b7c2685928/href">https://medium.com/media/94c56998d354bfed1db772b7c2685928/href</a></iframe><p>The framework creates real instances of both, AuthManager and LoginViewModel and then puts the one into the constructor of the other (where, again, all remaining dependencies are mocks by default).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/0*zG3YvC-P29hSVsTh" /></figure><p>In this manner, adding an integration test on top of already existing unit tests is very easy.</p><h3>Mocking</h3><p>In the setup function of the AuthManagerSteps you can see that there is some mocking code, too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a17c659583f0fcf6928bcae00507a27/href">https://medium.com/media/2a17c659583f0fcf6928bcae00507a27/href</a></iframe><p>In a normal unit test setup you’d rather use <a href="https://site.mockito.org/">mockito</a>’s thenReturn statement which receives a fixed value, as for static setup you just don’t need more than that. But for this example we’d rather do it in a dynamic way so that the stub actually responds to whatever scenario we want to have. Consequently, the mock can suit multiple scenarios and can be used from different places in the test code, e.g. from the AuthManagerTest <em>and</em> the integration test.</p><h3>Configuration</h3><p>Many things happen in the background when you use <a href="http://github.com/mysugr/sweetest">sweetest</a>, but some very minimal configuration is needed to make the automatic build-up of the dependency graph work for you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5648dc0b94275149b1cbf96a5fe1a7f/href">https://medium.com/media/a5648dc0b94275149b1cbf96a5fe1a7f/href</a></iframe><p>In this case all that is required is to tell the framework <em>which</em> types there are in the test scenarios, be it classes under test or dependencies of these classes. The constructors of all classes are examined automatically by means of reflection. Nothing more is required to get the automatic build-up of the dependency graph to work.</p><p>You can constrain whether specific classes can only exist as a mock in the dependency graph or as a real instance or actually both (any). So for example when you configure BackendGateway as mockOnly and you try to get a real instance of it you’ll face an exception during runtime as it’s not allowed anymore by configuration. For a backend gateway that is totally realistic, because it makes no sense to put it under unit test. Otherwise real communication to the internet would probably be happening, and that is what you usually don’t want for a unit test.</p><h3>Conclusion</h3><p>In the examples above you could see that many easy practices can be applied to writing test code right away. But <a href="http://github.com/mysugr/sweetest">sweetest</a> is especially good in helping to reduce all that nasty <strong>wiring of dependencies</strong>. Steps can be used to <strong>abstract </strong>technical implementation into small chunks of workflow, which then can be used as easy <strong>building blocks</strong> to create test setups. These can be used from <strong>different levels of tests</strong> like unit and integration tests. Test automation gives you great <strong>modularity</strong>, improves <strong>architecture</strong> and gives you a lot of <strong>confidence</strong> in your code, but <a href="http://github.com/mysugr/sweetest">sweetest</a> helps you in bringing all these benefits also to test code; not to speak of the great <strong>readability</strong> and <strong>maintainability</strong> you gain. When it’s your goal that you actually <em>like</em> coding tests, that’s what I think is needed.</p><p>We’re very proud to share this open source project with you! If you are curios, check out the example project you can find at the sources. If you want to give feedback feel free to comment here or on Github. We’re looking forward to all forms of contributions!</p><h3>What’s next?</h3><p>In follow-up posts I’ll show you more advanced topics on <a href="http://github.com/mysugr/sweetest">sweetest</a>, like best-practice patterns to follow, how to configure it and how to use IntelliJ best to keep the overhead of using this framework as low as possible. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5551e785f2ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monsterculture/sweetest-intro-5551e785f2ab">sweetest — create tests you actually love working with</a> was originally published in <a href="https://medium.com/monsterculture">Monster Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey to better test automation]]></title>
            <link>https://medium.com/monsterculture/a-journey-to-better-test-automation-9c33821c52fc?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c33821c52fc</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Fri, 21 Sep 2018 10:33:12 GMT</pubDate>
            <atom:updated>2018-10-09T13:34:28.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpdaPG2dBoHNg5QJHFhSIw.png" /></figure><p>Doing test automation right isn’t easy. And honestly, when you try to become good at it, it doesn’t make things easier in the first place. But similar to most investments for the future, it might hurt at first, but it pays off and gets you further in the long run.</p><p>At mySugr, test automation is an integral part of our work, as it is for any professional app or software company. But on top of that, parts of our app are classified as a medical device, which means that we are under regulatory control by authorities, therefore we care about quality even more. Facing these challenges we had to develop strategies within our agile environment to keep QA work doable. Naturally, things get more complex as your app grows.</p><p>Important questions were raised:</p><ul><li>In general: why doing test automation?</li><li>Can we get along with just unit tests? Is UI testing doing the trick? Or how do we get a proper distribution of the tests?</li><li>How do we manage a huge automated test suite?</li><li>How can we create and maintain tests more efficiently?</li></ul><p>Spoiler alert: we apply principles of clean code on testing. And for that we also have the new “sweetest” testing framework in place which is written in Kotlin and has just been <a href="https://github.com/mysugr/sweetest">open-sourced</a>, and there is an <a href="https://engineering.mysugr.com/sweetest-intro-5551e785f2ab">intro</a> on this blog, too; feel free to have a look!</p><h3>But why even bother?</h3><p>Some parts of our app needed to be done quickly so we needed to account for compromises. As a start-up, being quick can decide between life and death. So for these parts we sometimes had <strong>bad test coverage</strong>, which gave us some headache afterwards when we had to maintain and change stuff in the app. Refactoring without tests is like surgery with bad anaesthetization: it might hurt a lot and usually leads to complications. It affects you whether you’re a hobbyist coder or a multinational, but the bigger and older the app, the more it will hurt.</p><p>We <strong>relied on manual testing</strong> too much, which made us quite slow. No matter if you just run the app on your own to test a new feature or you have a department at hand which does it in a more professional manner, you always can fall into that trap. When you have to run your app to see if something is working as intended you’ve most likely already have fallen into it.</p><h3>So what will this be about?</h3><p>In this article I cover:</p><ul><li><strong>Advantages</strong> of automated over manual testing</li><li>How a good test automation strategy guides <strong>code design</strong></li><li>How we use different <strong>levels of testing</strong></li><li>What we believe is a <strong>good test</strong> and <strong>test architecture</strong></li><li>A new open-source <a href="https://engineering.mysugr.com/sweetest-intro-5551e785f2ab"><strong>testing framework</strong></a> that puts it all together</li></ul><h3>Manual vs. automated testing</h3><p>Automated testing is superior to manual testing in many ways. There is still (and there will always be) a need for manual testing, especially exploratory testing. But manual testing <strong>doesn’t scale well</strong> and QA people usually can’t tell you <strong>what and where exactly something went wrong</strong> in the code. Furthermore, <strong>continuous integration</strong> can speed up your development vastly, and manual testing can’t be integrated in that process. It’s also difficult to test <strong>data-intensive applications</strong> manually, or to test features that need a simulation of a scenario over multiple days or months.</p><h3>Tests guide your development</h3><p>It’s a <strong>big mistake</strong> to see test automation in software projects <strong>just as a QA or testing tool</strong>. Unit, integration and UI tests are in fact <strong>great design tools</strong>, and they also <strong>help to focus your efforts </strong>and <strong>increase maintainability</strong>. That way it <strong>speeds up development</strong> not just in the long run but from the initial stages. It’s not easy to see the benefits in the first instance, but I strongly advise to have a look at <strong>test-driven development</strong> and try to understand what it is really about. Most developers agree it’s a meaningful practice, but only a few give it a real chance. I like to see the test-first practice as a <strong>necessary progression step</strong> in a developer’s career and thus substantial for any software company.</p><h3>UI testing?</h3><p>In the beginning we thought that automated UI testing might solve our problem. It turned out that testing a mobile app end-to-end is not straightforward… Well, everyone makes mistakes! It <strong>costs</strong> a lot of time to write these tests, they tend to be <strong>flaky</strong> and when something breaks it’s very <strong>hard to analyse</strong> where the problem lies. That’s especially true for mobile apps in comparison to web apps.</p><p>But we learnt from our mistakes, so there is now a different approach: we test the UI of our app separately from the underlying business and presentation logic. Therefore, the sole purpose of a UI test is to check if the UI interacts correctly with the underlying presentation logic. There should be no business logic involved. I’ll cover this topic and the reasons in more depth in a separate post in this series — stay tuned!</p><p>So, no, UI testing is not the ultimate answer in mobile test automation!</p><h3>Distribute tests better</h3><p>A much more important key for us is to have a proper distribution of test levels, which is the best place to start. It makes no sense to start with UI testing when there’s still a lot to do at the unit and integration test level. The <a href="https://martinfowler.com/articles/practical-test-pyramid.html#TheTestPyramid">testing pyramid</a>, as described in an article by <a href="https://martinfowler.com/">Martin Fowler</a>, is our tool of choice to visualise the thought:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*VlHz2_ljIB7nyBbt" /><figcaption>Source: <a href="https://martinfowler.com/bliki/TestPyramid.html">Martin Fowler</a></figcaption></figure><ul><li>The basic idea is: <strong>unit tests</strong> are the cheapest to write, so we try to do most of the test automation at that level, may it be in the presentation, business logic, or data access layer of your app.</li><li><strong>Code integration tests</strong> are tests that check for the interaction between the units. They are more complicated to write but don’t have to be exhaustive, so we try to push edge cases down to the unit level wherever possible and just go for some easy cases on the integration level (e.g., a success and a fail case per functionality).</li><li><strong>System integration tests</strong> are similar but they run against the system, so the question such a tests should answer is: does the OS and the app communicate correctly with each other? These tests might be even a little more complicated to write and are definitely much slower as they have to run on physical or emulated devices.</li><li><strong>UI tests</strong> are an extension of this idea, they run on the operating system too but we are communicating with the user interface instead of the system API. UI tests are the most expensive to write, analyse and maintain and you should really have the proper strategy in place in order to make effective use of them.</li></ul><p>There are tons of articles on how to write proper tests in a relatively time-saving manner. Feel free to have a look and explore these concepts!</p><h3>What makes a good test?</h3><p>When you have placed your tests all at the right level there’s still the question how you notice a good test. Let yourself be guided by these questions:</p><ul><li>Is the test <strong>documenting</strong> the behaviour of the system under test?</li><li>Is it <strong>easy to read</strong> and <strong>self-explaining</strong>?</li><li>Is it <strong>well-factored</strong> like all other production code?</li><li>Are <strong>code duplications</strong> kept to a minimum?</li></ul><p>Of course, there are lists of other obvious factors like speed and predictability which are very important (you can find out a lot about that on the internet). But I’m trying to make a point here: We found out that, after taking all the obvious rules into consideration, we still couldn’t answer all questions with “yes”. So we came up with our new testing framework “<a href="https://github.com/mysugr/sweetest">sweetest</a>” which facilitates exactly these questions.</p><h3>“<a href="https://github.com/mysugr/sweetest">sweetest</a>” framework: organise tests better</h3><p>The aim of this framework is to <strong>reuse test code</strong> and make it <strong>easier to create test setups</strong>. It’s written in <strong>Kotlin</strong> and makes use of the nice language features it’s offering, where the possibility to write <strong>DSL-like</strong> code is especially worth mentioning. Reusing code comes with the cost of <strong>extra structures</strong>, of course, but we also end up with <strong>maintainable code</strong> that is <strong>easy to read and extend</strong>. With that in place, adding an integration test on top of a unit test or adding more edge cases are often just a <strong>matter of a few minutes</strong>.</p><p>This is an example on how a test with our neat little framework looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32cabc443e170b501cd655630afddf79/href">https://medium.com/media/32cabc443e170b501cd655630afddf79/href</a></iframe><p>AuthManager needs a bunch of other objects to function, namely a SessionStore and a BackendGateway. The <a href="https://github.com/mysugr/sweetest">sweetest</a> framework automatically generates a mock by means of the <a href="https://site.mockito.org/">mockito</a> framework for those. That’s of course a hint to <strong>dependency injection</strong>, which is naturally supported and it works perfectly together with DI frameworks like <a href="https://google.github.io/dagger/">Dagger</a>. In fact, it does its own dependency management, so you just have to tell it if a specific dependency should be initialized with a mock or a real instance. So, with an integration test, for example, you would just add additional dependencies to be real instead of mocked and then go on with putting together the already existing building blocks.</p><p>In order for all that to work, of course, you have to write these building blocks and put them into a class. This class then contains all mocking, setup, interaction and assertion logic for one class under test. I have to admit that it’s some extra work up front, but as I said earlier, that can be true for investments into the future; and with some template magic and the proper use of handy built-in IntelliJ features we can keep it to an absolute minimum. As always, it’s a matter of whether you see the benefits for yourself or are able to communicate them to your team.</p><p>In the <a href="https://engineering.mysugr.com/sweetest-intro-5551e785f2ab">follow-up post</a> in this blog I’ll show you that you just need two lines of code to configure an integration test setup with <a href="https://github.com/mysugr/sweetest">sweetest</a>, so stay tuned and let’s bring good architecture to test code!</p><h3>What’s next?</h3><p>If you want to know more about our test design considerations and see <a href="https://github.com/mysugr/sweetest">sweetest</a> in action, there will be more on this blog, like on</p><ul><li>how to use <strong>IntelliJ</strong> to make writing test code<strong> fast and easy</strong> (download the live template <a href="https://github.com/mysugr/sweetest#intellij-live-templates">here</a>)</li><li>how to <strong>write good test code efficiently</strong> (design considerations)</li><li>how to integrate <strong>Cucumber</strong></li><li>how we do <strong>UI testing</strong></li><li>how the framework works on the inside</li></ul><p>Also feel free to have a look at sweetest’s <a href="https://github.com/mysugr/sweetest">source code</a>, try it on your own, and of course to fork and contribute — it’s highly appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c33821c52fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monsterculture/a-journey-to-better-test-automation-9c33821c52fc">A journey to better test automation</a> was originally published in <a href="https://medium.com/monsterculture">Monster Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Draw before you code]]></title>
            <link>https://medium.com/monsterculture/draw-before-you-code-ca81d98374eb?source=rss-6ea1249ace5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca81d98374eb</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[drawing]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Marc Neureiter]]></dc:creator>
            <pubDate>Tue, 05 Dec 2017 13:59:24 GMT</pubDate>
            <atom:updated>2019-08-30T09:20:05.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Draw Before You Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eboG2ynnmDxBtS56UxwKsQ.jpeg" /></figure><p>Okay, I have to admit: I just wasted a whole sprint refactoring.</p><p>That’s no big deal in general: as long as it’s worth the effort, we really enjoy investing in quality at mySugr. But if you’re the same kind of programmer who not just has a lot of freedom at work, but also likes to produce really good code and architecture, you might end up with a big number of incremental micro-improvements, too — <strong>and a lot of wasted time</strong>!</p><p>As we write code, we learn constantly about new scenarios and potential for improvement of the feature we’re implementing. That’s totally normal — you can’t know everything in advance. But it’s not easy to cope with frequent change and by no way is it efficient; the same way we don’t like our product owners to change their opinion three times in a sprint.</p><h4>Therefore: Draw before you code!</h4><p>It only takes a few minutes. Just grab a piece of paper and draw your classes and the relations and interactions between them — just like that! When you think about a scenario and it’s not solvable with your architecture, drawing can help to work out the kinks.</p><p>Sure you have to invest more time, sometimes even a lot. That’s actually good because if you noticed the flaw during coding, you’d have to change your setting totally from <em>“yeah, coding!!!”</em> to <em>“oh stop, I need to rethink this and I probably have done unnecessary work”</em> — which is very uncomfortable. Every time you face a situation like that, you have to <strong>change focus,</strong> and sometimes you even have to make <strong>shortcuts</strong> or <strong>compromises</strong>.</p><p>In contrast, when you invest a few minutes beforehand to spend some thoughts on your architecture and probably discuss it with your colleagues, you will have much higher confidence about what you’re going to write. You’ve already taken all the edge cases and scenarios into account. Now you can concentrate on just writing down the classes and you don’t have to move stuff around until it “looks good.” Most likely, you’ll end up with much less distraction and a lot of time saved — welcome to the “zone!”</p><h4>The later you catch a flaw, the harder to fix.</h4><p>It goes without saying that it makes sense to draw a line between planning and execution. But for coding in an agile environment, it’s not always that obvious, especially when you’re self-taught or have an impulsive nature (which is a good thing, it just means that you really want to tackle the matter now and not later). But being ambitious about finally starting to code should never stop you from taking a deep breath and thinking it all through using the tools that help you most — even if it is just pen and paper.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca81d98374eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monsterculture/draw-before-you-code-ca81d98374eb">Draw before you code</a> was originally published in <a href="https://medium.com/monsterculture">Monster Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>