<?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 Danny Preussler on Medium]]></title>
        <description><![CDATA[Stories by Danny Preussler on Medium]]></description>
        <link>https://medium.com/@dpreussler?source=rss-1331e67af4e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Umz9XIuRPDF8AzokZZnndw.jpeg</url>
            <title>Stories by Danny Preussler on Medium</title>
            <link>https://medium.com/@dpreussler?source=rss-1331e67af4e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:12:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dpreussler/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[Software craftsmanship in the age of agentic coding]]></title>
            <link>https://proandroiddev.com/software-craftsmanship-in-the-age-of-agentic-coding-54e2b85f740c?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e2b85f740c</guid>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[software-craftsmanship]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 14:10:12 GMT</pubDate>
            <atom:updated>2026-10-27T18:04:22.821Z</atom:updated>
            <content:encoded><![CDATA[<p>What does software craftsmanship mean in the age of agentic coding? I went looking for answers and left with more questions, along with a surprising amount of optimism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoVL_FthYQMHySTfRbHsmw.png" /><figcaption>Source: <a href="https://bsky.app/profile/socrates-crete.org/post/3myn6e74cwc2n">https://bsky.app/profile/socrates-crete.org</a></figcaption></figure><p>AI is transforming our field. Contrary to the apocalyptic predictions from six months ago, most of us haven’t lost our jobs. In fact, companies are still struggling to measure any real productivity boost, at least in terms of user value or revenue. Yet, how we work is fundamentally changing, and that shift can feel unsettling.</p><p>As I felt similarly, it was time to step out of my bubble. Nearly ten years ago, I used to attend Software Crafters events across Europe. I remembered meeting deeply knowledgeable engineers, not the “rockstars” dominating LinkedIn feeds, but people who cared about their craft. So it was time again to reconnect with them. Therefore, I booked a flight to Greece for SoCraTes Crete, which took place in a seaside resort: no stages, no pre-packaged slides, just attendees sharing experience, questions, and conversation.</p><p>It was naive to expect the future to be mapped out neatly over a weekend. Actually, everyone arrived with similar questions. At times, it felt like group therapy for programmers who don’t get to program anymore, trying to answer: <em>How do we keep the joy of our work?</em></p><p>As someone who still enjoys his work, I realized the answer to that question depends on where you take the joy from. Are you proud of the <strong>what</strong> (the value delivered to users), or the <strong>how</strong> (the elegance of the implementation)? When your pride is tied to the mechanics of the <em>how</em>, today’s shift feels existential.</p><p>Which brings us to the core issue: what craftsmanship actually means now? As part of that, in one of my sessions I asked: <em>Is TDD dead (again)?<br></em>For the classic red-green-refactor micro-cycles, it probably is dead; we had to agree. Trying to force an agent into small, incremental loops just is no fun, for the agent nor us.<br>If we think as “test-first,” where humans write the specs and agents implement the solution, this still works. But who guards the test suite against an agent quietly modifying them? As we’ve seen from the Hugging Face incident, models will take shortcuts.</p><p>Let’s face it: AI is pretty good at generating unit tests itself; mapping well-defined inputs to expected outputs is precisely what these models are intended to do.</p><p>I met a few developers there who choose not to use AI much. In settings like mob programming, the friction of agentic tools breaks the team’s flow. And as long as we haven’t figured out the problem of code reviews or better quality gates for generated code, such “human” teams aren’t falling behind; they might even be faster.</p><p>Still, the consensus was clear: agentic development isn’t going away.</p><p>So what becomes of our roles? Are we just kept around to click “approve” so there is someone to take the blame when things go sideways?</p><p>We found a helpful analogy from outside software: aviation. Airplanes have been capable of navigating, flying, and landing autonomously for decades. Yet pilots remain in the cockpit; they train continuously. They aren’t there to be scapegoats; they exist as the ultimate safety net. Engineers might be those safety nets. We need a harness, linters, test suites, and experienced human judgment.</p><p>Open space events like SoCraTes have their rules too. The Law of Two Feet (sometimes called the Law of Mobility) states: If you are at any time in a place where you are neither learning nor contributing, use your two feet to go somewhere else. It’s ok to move somewhere else. This way you also know the ones staying are actual interested and not prompting instead like, let’s be honest, we do a lot during meetings. Add in simple practices like handwritten kudo cards to thank someone for their contributions, help, or attitude, and you’re reminded of the human connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsXAPI96wc8X6HIv_arZWw.jpeg" /></figure><p>I arrived hoping for answers and left with a stack of new questions. I left energized, looking positively into the future.</p><p>Surrounded by the Cretan sun, the beach, and engineers who care deeply about what they’re building, the “software apocalypse” felt further away as long as we’re all navigating this transition together.</p><p><strong>PS:</strong> In the evenings, someone spotted the Ableton Move I had brought along. I’d owned it for a while but felt too intimidated to dig in. A few of us sat down, stumbled through some truly awful noises, and eventually pieced together tracks we were actually proud of. Much like navigating new tech shifts, figuring things out in a group makes the steep curve a lot more fun. <a href="https://soundcloud.com/cosmic_bald/gettingstarted">Here are my first few tunes on SoundCloud</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e2b85f740c" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/software-craftsmanship-in-the-age-of-agentic-coding-54e2b85f740c">Software craftsmanship in the age of agentic coding</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interpreting voice results for Android media apps in cars]]></title>
            <link>https://proandroiddev.com/interpreting-voice-results-for-android-media-apps-in-cars-f36d7bdb26e1?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f36d7bdb26e1</guid>
            <category><![CDATA[google-assistant]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-auto]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 21:33:42 GMT</pubDate>
            <atom:updated>2022-01-12T21:18:15.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlwLUUZnAwzJ9o6MM7vUgg.jpeg" /></figure><p>When working on the Android Auto integration for SoundCloud, I stumbled upon an interesting issue. When it comes to implementing voice actions, things you read in the documentation might differ a bit from reality.</p><p>Voice commands are very critical while driving a car. You want the driver to keep looking at the street, keep his hands on the steering wheel, instead of interacting with any screen. This is why when building for <a href="https://developer.android.com/cars">Android Auto, Automotive OS</a>, and <a href="https://developer.android.com/guide/topics/media-apps/assistant-driving-mode">Assistant Driving Mode</a> you have to support basic voice searches.</p><p>For a music app like ours, the idea is simple. A user can say something like:</p><p><em>“Play Moderat on SoundCloud”</em></p><h4>Under the hood</h4><p>The Assistant will break down our sentence for interpretation:</p><p>“<em>&lt;Play&gt; &lt;Moderat&gt; &lt;on SoundCloud&gt;</em>”</p><p>The verb (Play) and the app (SoundCloud) in the above command were meant for the system. It will then wake up the app mentioned (if it declared auto support via manifest) and, as we asked for verb “Play”, the method MediaSessionCompat.Callback.onPlayFromSearch() will be called with the remaining query (“<em>Moderat</em>”) as the argument.</p><p>This query of “what to play” can still mean different things though. How do you know if Moderat is a band or a song? Don’t worry, the Assistant will help us also here. It already got some idea what our query could mean, if we asked for an artist, an album, or a specific track. But be aware<strong>, it behaves slightly differently than officially documented.</strong></p><p>According to <a href="https://developer.android.com/guide/topics/media-apps/interacting-with-assistant#parse_voice">documentation</a> we are supposed to write code like this:</p><pre>val mediaFocus = extras?.<strong>getString(MediaStore.EXTRA_MEDIA_FOCUS)</strong><br>if (mediaFocus == MediaStore.Audio.<strong>Artists.ENTRY_CONTENT_TYPE</strong>) {<br>  isArtistFocus = true<br>  artist = extras.getString(<strong>MediaStore.EXTRA_MEDIA_ARTIST</strong>)</pre><p>We are suppose to check for a bundle entry with the key MediaStore.EXTRA_MEDIA_FOCUS . This will give us a hint on how best to interpret the query. The value of the constant MediaStore.EXTRA_MEDIA_ARTIST checked above is vnd.android.cursor.item/artist and there are similar constants related to album name, song title. In theory all you have to to is match the mediaFocus against one of those.</p><h4>Unfortunately, this <strong>doesn&#39;t work like intended!</strong></h4><p>In reality, you will <strong>always</strong> get the valuevnd.android.cursor.item/* . This does not even exist as a constant in the SDK but it is exactly the value you will be getting as the focus param from Assistant for now. Even a Google search will not bring us very far here, which is the main reason I’m writing this.</p><p>Why? This is a question I can not answer. Maybe it was working like this somewhen in the past. I opened an <a href="https://issuetracker.google.com/issues/212779546">issue</a>, that hopefully will put some light into this, feel free star and/or follow.</p><h4>What now?</h4><p>This doesn’t mean that we are completely lost though. <br>Let’s look at a more complex query:</p><p><em>“Play Live from Moderat on SoundCloud”</em></p><p>The system actually gives us some hints about that query. Let’s check the entries of the Bundle we got in or callbackonPlayFromSearch.<br>Of course, we will see, what we just talked about, the weird media focus entry:<br>android.intent.extra.focus -&gt; vnd.android.cursor.item/*</p><p>We also have access to the pure and the extracted query:</p><p>android.intent.extra.user_query -&gt; Play live from moderat on soundcloud</p><p>query -&gt; live moderat</p><p>But the interesting part is the following:</p><p>android.intent.extra.artist -&gt; Moderat<br>android.intent.extra.title -&gt; Live</p><p>The Assistant figured out that one part is probably a band and one a title.<br>There are more intent-extras like this that can be used to find the right entity such as android.intent.extra.title, android.intent.extra.artist, android.intent.extra.album etc.<br>And these are actually also stated in the documentation:</p><blockquote>The following extras are supported in Android Automotive OS and Android Auto:<br><a href="https://developer.android.com/reference/android/provider/MediaStore#EXTRA_MEDIA_ALBUM">EXTRA_MEDIA_ALBUM</a><br><a href="https://developer.android.com/reference/android/provider/MediaStore#EXTRA_MEDIA_ARTIST">EXTRA_MEDIA_ARTIST</a><br><a href="https://developer.android.com/reference/android/provider/MediaStore#EXTRA_MEDIA_GENRE">EXTRA_MEDIA_GENRE</a><br><a href="https://developer.android.com/reference/android/provider/MediaStore#EXTRA_MEDIA_PLAYLIST">EXTRA_MEDIA_PLAYLIST</a><br><a href="https://developer.android.com/reference/android/provider/MediaStore#EXTRA_MEDIA_TITLE">EXTRA_MEDIA_TITLE</a></blockquote><p>As result just ignore the code sample part of the documentation, ignore MediaStore.EXTRA_MEDIA_FOCUSand use those values instead.</p><p>Just grab them all and then check which values are non null</p><pre>val artist = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST)<br>val album = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM)<br>val title = extras.getString(MediaStore.EXTRA_MEDIA_TITLE)</pre><p>If the user asked for an album, you probably will have a valid value in album and artist, otherwise use artist and title or simply the title…</p><h4>Sum up</h4><p>As said, it is unclear to me why the focus is not forwarded to the apps as shown. Even, the <a href="https://github.com/android/uamp/blob/99e44c1c5106218c62eff552b64bbc12f1883a22/common/src/main/java/com/example/android/uamp/media/library/MusicSource.kt">Universal Media Application from Google</a> uses the focus parameter similar to the documentation, which might mean this worked at some point.</p><p>In the end remember, always make sure you are actually testing all parts of your implementation! Code that was implemented as stated in the documentation, might still not actually work.</p><p><a href="https://issuetracker.google.com/issues/212779546">https://issuetracker.google.com/issues/212779546</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f36d7bdb26e1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/interpreting-voice-results-for-android-media-apps-in-cars-f36d7bdb26e1">Interpreting voice results for Android media apps in cars</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Kotlin standard library in Java]]></title>
            <link>https://medium.com/google-developer-experts/using-the-kotlin-standard-library-in-java-ea0766deac10?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea0766deac10</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Mon, 14 Jun 2021 19:01:08 GMT</pubDate>
            <atom:updated>2021-06-15T13:42:00.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using the Kotlin standard library from Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*EdIWoW0eBz8cYdyi.gif" /><figcaption>giphy.com</figcaption></figure><p>If you work with Kotlin on a daily basis you probably love the language and don’t want to go back to Java. Though, many of us work on a codebase that isn’t purely Kotlin. Our Android codebase at <a href="https://soundcloud.com/">SoundCloud</a> still has a fair amount of code written in Java. This percentage gets smaller over time but there is no urgent need for mass migration of the remains right now.</p><p>Therefore, every once in a while, I find myself, changing Java files. In those cases, I miss some of the Kotlin functions I’m used to; I can easily think of string manipulation or handling collections as examples. Of course, Java has powerful utility libraries such as <a href="https://github.com/google/guava">Googles Guava</a> or <a href="https://commons.apache.org/proper/commons-collections/">Apache Commons</a>, libraries many of which we used to work with in the world before Kotlin.</p><p>But when writing Kotlin code all day, remembering those “older” APIs is sometimes hard. It is a complete context switch. It would be much easier to use what we use in Kotlin. And you should! Let me show you!</p><p>Let’s assume we want to create a list of items. In Kotlin, we would write:</p><pre>val<strong> </strong>items<em> </em>= <strong><em>listOf</em>(<br>    items1, item2, item3<br>)</strong></pre><p>In Java, I would write it as:</p><pre>List&lt;Item&gt; items = <strong>Arrays.<em>asList</em></strong>(item1, item2, items3);</pre><p>Usage is pretty much the same but you still need to remember the name of the function. Wouldn’t it be easier to just use:</p><pre>List&lt;Item&gt; items = <strong>listOf(</strong>item1, item2, items3);</pre><p><strong>And yes you can!</strong></p><p>All you need to do is to static importthat function! This works aslistOf, like many of our daily Kotlin utility functions, are simply static functions you can use from Java.</p><p>And even better, as your project already uses Kotlin, you already got those dependencies included anyway, no additional library needed.</p><h3>A closer look</h3><p>If you would click on the details of listOf<strong> </strong>from Kotlin, you would end up in a file called Collections.kt and the definition looks like this:</p><pre>public <strong>fun</strong> &lt;T&gt; <strong>listOf</strong>(vararg elements: T)<strong>: List&lt;T&gt;</strong></pre><p>It is a free function, not bound to any class. But from a Java perspective this looks something like this:</p><pre>public final <strong>class CollectionsKt</strong> {<br>   @NotNull<br>   <strong>public static</strong> final List&lt;T&gt; <strong>listOf</strong>(@NotNull T... elements) {<br>   ...<br>} </pre><p>Where does this class come from? Note that a function not bound to a class from Kotlin still has to be put into a class in bytecode. In this case, the functions from the file Collections.kt will simply end up in a class called CollectionsKt. <br>And in doubt, if you want to know the class name you need to static import in Java, simply go to the declaration of your Kotlin function and check the file name.</p><h3>Extension function</h3><p>What about extension functions? In my opinion, those are one of the most powerful tools Kotlin offers. From a Java point of view, extension functions are also just static functions where the receiver becomes the first argument. Let‘s look at an example:</p><pre>validItems<em> = </em>items<strong>.filterNotNull()</strong></pre><p>filterNotNull is an extension function, as we can see in the declaration:</p><pre>public fun<strong> </strong>&lt;T : Any&gt; <strong>Iterable&lt;T?&gt;.filterNotNull</strong>(): List&lt;T&gt;</pre><p>From Java this looks something like this:</p><pre><strong>public static </strong>final<strong> </strong>List&lt;T&gt; <strong>filterNotNull</strong>(@NotNull Iterable&lt;T&gt; $this$filterNotNull)</pre><p>The usage would look like this:</p><pre><em>validItems = filterNotNull</em>(items);</pre><p>That’s not too bad, is it?</p><p>The only drawback when using extension functions from Java is that you can’t concatenate calls with other extension functions like you would do in Kotlin:</p><pre>items.filterNotNull().find{...}.map{...}</pre><p>This won’t work in Java, as we learned: the receiver becomes the first argument, so we would need to rewrite this to multiple lines of code. But each of the functions can be used though.</p><h3>Side note</h3><p>If you would look further into this example, you might notice that thefilterNotNull function sits in a file called _Collections.kt not Collections.kt. Still, we import the class CollectionsKt , the same name as we used to above. This is as the authors defined the target class name explicit via an annotation: @file:kotlin.jvm.JvmName(“CollectionsKt”)</p><h3>Costs</h3><p>You might ask if there are any hidden costs when using these Kotlin libraries from Java. The answer is simple: no! Kotlin libraries come in byte code like every library written in Java. The only thing you probably won&#39;t find in a normal Java library would be the null checks. Similar to when moving to Kotlin, be aware of sudden exceptions when passing null where it was not expected.</p><h3>Summary</h3><p>Many functions in Kotlin are implemented as extension functions and can easily be used from Java via static imports. You might not be able to use all of Kotlin&#39;s power, especially thinking of functionalities like Coroutines. Calling standard functions is not a problem though and should be used more often. And you might even get rid of some third-party libraries only used for Java.</p><p>Using the same function reduces the <a href="https://en.wikipedia.org/wiki/Cognitive_load">cognitive load</a> for the team when working on mixed codebases. This is even more valuable with developers starting directly with Kotlin without having a long Java background which we will see more and more.</p><p>But let me remind you that this tip is for that intermediate state when your codebase is not fully Kotlin yet. If you have a Java project and planning with Java long term, using Kotlin libraries should not be your strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea0766deac10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-developer-experts/using-the-kotlin-standard-library-in-java-ea0766deac10">Using the Kotlin standard library in Java</a> was originally published in <a href="https://medium.com/google-developer-experts">Google Developer Experts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The modifier that shouldn't be there]]></title>
            <link>https://proandroiddev.com/the-modifier-that-shouldnt-be-there-77ff941f0529?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ff941f0529</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Mon, 31 May 2021 14:15:00 GMT</pubDate>
            <atom:updated>2021-06-01T13:42:29.501Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Kotlin modifier that shouldn&#39;t be there</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPf7UbrPTvwSQ8xQ3v_aJA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bel2000a?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Belinda Fewings</a> on <a href="https://unsplash.com/s/photos/unexpected?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Most Kotlin developers would agree that a val property is equivalent to a final property in Java. What if I tell you that this is not completely true and sometimes you might need a final val?</p><p>Opposite to Java, Kotlin properties are final by default unless they are explicitly marked as open! This would mean there is no need for the final keyword, right? Let’s Google that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTOBwgKh4Yp1Bn9KxG6o1g.png" /></figure><p>As the internet confirmed our hypothesis, I was quite surprised when Android Studio told me to addfinal to a val:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgMOm-cWnTLdEPIo__WCcw.png" /></figure><p>and indeed adding final would fix that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*33ITNiup6efFCcjf0ax-Cg.png" /></figure><p>So there is a final keyword for properties but why and when should we make a val final?</p><p>Let’s look at this behavior using a simple example:</p><pre><strong>class</strong> FinalBlog {<br><br><strong>    val someProperty: String</strong> = &quot;some&quot;<br><br>    init {<br>        <em>print</em>(<strong>someProperty</strong> + &quot;thing&quot;)<br>    }<br>}</pre><p>“Everything works as expected here and the code will print “<em>something</em>” when the class is instantiated.</p><p>Let’s modify everything to be open:</p><pre><strong>open class </strong>FinalBlog {<br><br>    <strong>open val someProperty</strong>: String =<strong> </strong>&quot;some&quot;<strong><br><br>   </strong> init {<br>        <em>print</em>(<strong>someProperty</strong> + &quot;thing&quot;)<br>    }<br>}</pre><p>This will trigger the same type of warning I got before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z10NQVem-wKaI_bO0MHfCw.png" /></figure><p>This is very obvious when you think about it. The class can be subclassed and our property might be overridden. This could lead to unexpected side effects (which we will look into at the end of this post.). <br>We can fix this simply by removing theopen modifier from the field. So, althought the warning has the same cause, it’s not the exact same scenario my Android Studio was warning me on, there is no way I could add final here: non open already means final!</p><p>Let’s try something else:</p><pre><strong>interface </strong>BlogTopic {<br>    <strong>val someProperty: String</strong><br>}<br><br><strong>open class </strong>FinalBlog: BlogTopic {<br><br>    <strong>override val someProperty</strong>: String = &quot;some&quot;<strong><br><br></strong>    init {<br>        <em>print</em>(<strong>someProperty</strong> + &quot;thing&quot;)<br>    }<br>}</pre><p>If the property is inherited from an interface, then it’s open by default! <br>Again, we will get the warning, we were looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpWGsmeOar-T5AOPf8D0Yw.png" /></figure><p>And this time adding the final modifier will fix it:</p><pre><strong>open class </strong>FinalBlog: BlogTopic {<br><br>    <strong>final override val someProperty</strong>: String = &quot;some&quot;<strong><br><br>    </strong>init<strong> </strong>{<br>        <em>print</em>(<strong>someProperty</strong> + &quot;thing&quot;)<br>    }<br>}</pre><p>Voila, we got a final val 🥳</p><p>You will probably ask now: but in the original code, it was not an overridden val. Indeed, and also I didn&#39;t declare my class open!</p><p>The mystery has a simple solution: When I checked my class, I saw it:</p><pre><strong>@OpenForTesting<br></strong>class<strong> </strong>FindPeopleToFollowViewModel</pre><p>This is a commonly used marker that will trigger the <a href="https://kotlinlang.org/docs/reference/compiler-plugins.html#all-open-compiler-plugin">Kotlin compiler plugin </a>to open our class for testing so that they can be mocked there. But this opens up your class and makes every single field open, independent of test scope or not. And this is how I did see a val that actually will be open although I did not write it like this.</p><p>Hope you enjoyed this little excurse and if you also use that compiler plugin: You might want to consider <a href="https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#mock-the-unmockable-opt-in-mocking-of-final-classesmethods">mock maker inline from Mockito</a> instead. Or, even better, try to use fewer mocks then you won&#39;t need this in the first place (<a href="https://www.youtube.com/playlist?list=PLqew6vQ7CzHIUNy7VjCG8-N0Z2xjT7qrr">TDD</a> helps with that). 🤓</p><h3>Aftermath</h3><p>If we look at the example from above:</p><pre><strong>open class </strong>FinalBlog: BlogTopic {<br><br>    <strong>override val someProperty</strong>: String = &quot;some&quot;<strong><br><br>    </strong>init<strong> </strong>{<br>        <em>print</em>(<strong>someProperty</strong> + &quot;thing&quot;)<br>    }<br>}</pre><p>Now let’s extend that class:</p><pre>class <strong>ChildBlog: FinalBlog</strong>() {<br>    <strong>override val someProperty </strong>= <strong>&quot;another &quot;<br></strong>}</pre><p>What do you think it will print once we initialize this class?</p><p>“<em>something</em>” or “<em>another thing</em>”?</p><p>Actually, it prints “<em>nullthing</em>”! 🤯</p><p>This is what the warning was trying to tell us! To understand this issue, let’s jump into the byte code. (I use the “show Kotlin bytecode” and then choose the “decompile” to read it in Java format)</p><pre>public class FinalBlog implements BlogTopic {<br>   @NotNull<br><strong>   private final String someProperty</strong> = &quot;some&quot;;</pre><pre>   @NotNull<br><strong>   public String getSomeProperty()</strong> {<br>  <strong>    return this.someProperty;<br>   }</strong></pre><p>Our Kotlin property is a getter with a field to hold the content.</p><p>Same for the child class:</p><pre>public final class <strong>ChildBlog extends FinalBlog</strong> {<br>   @NotNull<br>   <strong>private final String someProperty = &quot;another &quot;;</strong><br><br> <strong>  @NotNull<br>   public String getSomeProperty() {<br>      return this.someProperty;<br>   }</strong><br>}</pre><p>The problem is that we access the value from the parent constructor. As the getter is overridden, the version from the child class will be called. But the backing field is not initialized yet as we are still in the super constructor call. Therefore the value is null. (for a non-null declared field!).</p><p>But if we would have implemented the class without the backing field:</p><pre>class ChildBlog: FinalBlog() {<br>    <strong>override val someProperty<br>        get</strong>() = <strong>&quot;another &quot;<br></strong>}</pre><p>It would work. So the behavior is really unpredictable! Do not access non-final fields from the constructor.</p><p>Please keep an eye on warnings, they are there to help you!</p><p>PS: Thanks the all the amazing reviewers mentioned below plus <a href="https://medium.com/u/bf0c422f54a">mvndy</a> for proofread and discussion</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ff941f0529" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-modifier-that-shouldnt-be-there-77ff941f0529">The modifier that shouldn&#39;t be there</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid backing properties for LiveData and StateFlow]]></title>
            <link>https://medium.com/google-developer-experts/avoid-backing-properties-for-livedata-and-stateflow-706006c9867e?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/706006c9867e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 14:03:52 GMT</pubDate>
            <atom:updated>2021-01-14T14:24:52.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-pzXHtf0_BBtplpDb257g.jpeg" /><figcaption><a href="https://unsplash.com/photos/OopPIi_A428">https://unsplash.com/photos/OopPIi_A428</a></figcaption></figure><p>If you have ever worked with <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a> you probably have written code similar to this:</p><pre>class MyViewModel: ViewModel() {</pre><pre><strong>   val loading: LiveData&lt;Boolean&gt;<br>       get() = _loading</strong></pre><pre><strong>   private val _loading = MutableLiveData&lt;Boolean&gt;()</strong></pre><pre>}</pre><p>This seems nowadays the typical way developers would expose some immutable LiveData, while being able to have a mutable version inside the implementation we would write data into.</p><p>Every time I saw, or even had to write, this kind of code something cringed inside me. As I quoted in <a href="https://speakerdeck.com/dpreussler/take-your-kotlin-to-the-next-step-abandon-what-youve-learned-in-java">one of my talks</a> this feeling in our brain is for real:</p><blockquote><a href="https://sciencephenomena.wordpress.com/2015/05/10/the-neurological-aspect-of-cringing/"><em>social missteps activate regions in the brain, [..] that have been previously associated with physical pain.</em></a></blockquote><p>As developers, we know something is wrong with this code, right? It also feels like we are writing manual getters and setters here.</p><h3>What’s wrong?</h3><p>We could start with the prefix we use for the backing field, although we fought hard for a long time to get rid of prefixes, we accept it here! It is even made it into the <a href="https://kotlinlang.org/docs/reference/coding-conventions.html#property-names">official coding conventions</a>.</p><p>But even if we rename it, it still cringes:</p><pre>class MyViewModel: ViewModel() {</pre><pre>   val <strong>loading</strong>: LiveData&lt;Boolean&gt;<br>       get() = <strong>mutableLoading</strong></pre><pre>   private val <strong>mutableLoading</strong> = MutableLiveData&lt;Boolean&gt;()</pre><pre>}</pre><p>This duplication feels unneeded! Especially if you write something like a ViewModel that exposed many of these, you get lost in reading the code just by all these duplications.</p><h3>But it&#39;s just LiveData?</h3><p>You might think it’s just a specialty of LiveData and the future of that construct might be a more limited one.</p><p>And you would not have this issue with primitives. The language supports this out of the box with a private setter:</p><pre>var secret: String = &quot;Secret&quot;<br>  <strong> private set</strong></pre><p>But there is a new kid in town: StateFlow needs the same thing! Look at this snippet from the official <a href="https://blog.jetbrains.com/kotlin/2020/10/kotlinx-coroutines-1-4-0-introducing-stateflow-and-sharedflow/">Jetbrains blog</a>:</p><pre>class DownloadingModel {</pre><pre><strong>   private val _state</strong> = MutableStateFlow&lt;DownloadStatus&gt;(DownloadStatus.NOT_REQUESTED)</pre><pre><strong>   val state: StateFlow&lt;DownloadStatus&gt; get() = _state</strong></pre><p>This problem is discussed a lot. Some even <a href="https://youtrack.jetbrains.com/issue/KT-14663">suggested a change in the Kotlin </a>language to support this!</p><p>Though it feels like we want to use a sledgehammer to crack a nut or shoot with cannons into sparrows or whatever that term in your language!</p><p>Isn’t there is something more subtle to solve this?</p><h3>What is our actual goal?</h3><p>We want to separate the public API from the actual implementation, right?</p><p>Believe it or not, we already have a language construct for this! It’s called <strong>Interface</strong>!</p><p>Although many developers would extract interfaces regularly for classes like Repositories, hardly anyone does for ViewModels.</p><p>Why is that? Because there is only one implementation? Maybe as of ViewModels are the last building block before the view, we hardly ever need to mock them in tests? <br>Maybe! But we just found another good reason to use them.</p><p>For the case for ViewModel an abstract class would make it easier as we need to extend Googles ViewModel anyway (you can use interfaces though if you prefer)</p><pre>abstract class MyViewModel: ViewModel() {<br><strong>   abstract val loading: LiveData&lt;Boolean&gt;</strong><br>}</pre><pre>class MyViewModelImpl: MyViewModel() {<br><strong>   override val loading = MutableLiveData&lt;Boolean&gt;()</strong><br>}</pre><p>From inside the ViewMode has now the type:<br>override val loading: <strong>MutableLiveData&lt;Boolean&gt;</strong></p><p>This is called <a href="https://en.wikipedia.org/wiki/Covariant_return_type#:~:text=In%20object%2Doriented%20programming%2C%20a,is%20overridden%20in%20a%20subclass.&amp;text=This%20usually%20implies%20that%20the,type%20of%20the%20overridden%20method.">covariant return types</a>, where the implementation returns a more specific type than the original declared. The nice thing now is, that we can directly set values onto our loading state from within our implementation:</p><pre>class MyViewModelImpl: MyViewModel() {<br><strong>   </strong>override val loading = <strong>MutableLiveData</strong>&lt;Boolean&gt;()</pre><pre>   fun doSomeWork() {<br>     // ...<br><strong>     loading.value = true<br></strong>  }<br>}</pre><h3>Isn’t it leaking details?</h3><p>You might ask if we aren’t exposing too many implementation details? <br>If you would use MyViewModelImpl directly (and not the abstract class), you could write into the loading from outside!</p><p>The answer is <strong>no</strong>!</p><p>No one except for whoever creating the class should know about it anyway! Normally this would be the layer we do dependency injection or, in the case of ViewModels, the ViewModelFactory. Try to even avoid making it possible to see or create the implementation directly.</p><p>Of course, someone can always upcast the interface to the concrete class but could have also upcasted the original loading anyway!</p><p>Quoting an older clean coders blog here:</p><blockquote><strong><em>Who would do that? </em></strong><em><br>I dunno. Uh. Someone bad.</em></blockquote><blockquote><strong><em>Do you have bad people on your team?</em></strong><em><br>No. But. This just doesn’t feel safe.</em></blockquote><blockquote><strong><em>Well, if this were part of a public API, I’d agree with you. But if this is just code that’s used by our team then…</em></strong></blockquote><p>We don’t need to protect our code against bad actors if those are just our colleagues. Our job is to make sure the API is clear and clean so the usage understandable! Focus on preventing mistakes, not abuse.</p><h3>Specifics for Google’s ViewModel</h3><p>ViewModels from Jetpack have some specifics, let’s briefly discuss where to use the abstract class there.</p><p>If you use Koin its trivial:</p><pre>private val<strong> </strong>viewModel: <strong>MyViewModel by <em>viewModel</em>()</strong></pre><p>in your module you would then declare it like:</p><pre>viewModel<strong>&lt;MyViewModel&gt;</strong> { <strong>MyViewModelImpl</strong>(...) }</pre><p>When using the delegates from Ktx things are a bit more tricky sometimes (<a href="https://proandroiddev.com/testing-the-untestable-the-case-of-the-viewmodel-delegate-975c09160993?source=your_stories_page-------------------------------------">like testing</a>). <br>It is easy though if you use a custom provider, which could be injected by Dagger for example:</p><pre>@Inject lateinit var provider: <strong>MyViewModelProvider</strong><br>private val viewModel: <strong>MyViewModel by <em>viewModels </em></strong>{ provider }</pre><p>It’s not as obvious if you use the generic factory:</p><pre>@Inject lateinit var factory: <strong>ViewModelProvider.Factory</strong><br>private val viewModel: <strong>MyViewModel by <em>viewModels</em></strong><em> </em>{ factory }</pre><p>You have to tell Dagger somehow how to do the matching. But should be done just the normal way in your module where you would bind MyViewModel to MyViewModelImpl either manually or with @Bind . It means more Dagger code but less code in the ViewModel, which should be worth it. When it comes to Dagger sometimes <em>more</em> is better if it improves your overall architecture. Focus on improving the code you read and work daily with, not the Dagger setup behind the scenes.</p><h3>Conclusion</h3><p>By using interfaces or abstract classes you not only get rid of all the duplications in the implementation but can focus on the functionality as well. Reducing noise is very important for clean and reusable code.</p><p>Plus, you create a very clean API for your users, here one from a small Quiz app I was working on, using Flow:</p><pre>abstract class GameViewModel: ViewModel() {<br>    val nextQuestion: Flow&lt;String&gt;<br>    val nextAnswers: Flow&lt;Answers&gt;<br>    val loadingVisible: Flow&lt;Boolean&gt;<br>    val score: Flow&lt;String&gt;<br>    val gameOver: Flow&lt;Boolean&gt;<br>}</pre><p>And if you think back to C programming with header files, this is what we had back then. A clear interface to the outside world, perfect encapsulation. <br>A forgotten art sometimes…</p><p>PS: All the credit goes to <a href="https://medium.com/u/95a5d2c71eff">Aidan Mcwilliams</a> who put my attention onto this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=706006c9867e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-developer-experts/avoid-backing-properties-for-livedata-and-stateflow-706006c9867e">Avoid backing properties for LiveData and StateFlow</a> was originally published in <a href="https://medium.com/google-developer-experts">Google Developer Experts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When “Compat” libraries won’t save you]]></title>
            <link>https://proandroiddev.com/when-compat-libraries-do-not-save-you-dc55f16b4160?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc55f16b4160</guid>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 19:34:03 GMT</pubDate>
            <atom:updated>2021-01-07T07:40:05.528Z</atom:updated>
            <content:encoded><![CDATA[<p>And why you should avoid using the “<em>NewApi</em>” suppression!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UZ7BojQmk2vRCTx6XIdLA.jpeg" /><figcaption><a href="https://unsplash.com/photos/EgGIPA68Nwo">https://unsplash.com/photos/EgGIPA68Nwo</a></figcaption></figure><p>The idea of “Compat” libraries was probably one of the key aspects of Android dominating the mobile space. Other than with iOS, Android users often could not update their operating system after a new version launch, simply as their phones won’t allow them to, the Android problem of <a href="https://www.androidauthority.com/android-fragmentation-linux-kernel-1057450/">fragmentation</a>. But developers still wanted to use the latest features to compete. The solution was simple: instead of adding new APIs to the operating system, you shipped those directly with your app by using a “backport” version Google gave you.</p><p>It all started with <a href="https://github.com/JakeWharton/ActionBarSherlock">ActionBar Sherlock</a> by <a href="https://medium.com/u/8ddd94878165">Jake Wharton</a> then got adopted by Google with in their “support libraries”. Later on, this was mirrored as <em>AndroidX</em> under the <em>Jetpack</em> umbrella.</p><h3>Same but different</h3><p>Under the hood, not all of those “compat”-APIs are made the same way. Some, like the ones for Fragments, are complete copies of the code. You either use android.app.Fragment from the OS (actually deprecated) or androidx.fragment.app.Fragment. Both don&#39;t share any code or have a common base class (which is why we also have two versions of the FragmentManager).</p><p>On the other handAppCompatActivity for example, simply extends the original Activity. AlsoAppCompatImageButton still is an ImageButton!</p><p>We can see that sometimes these “Compat”-classes are just a “bridge” to add missing functionalities and sometimes they are complete duplicates.</p><h3>Let’s look at another example!</h3><p>One area that changed a lot over time is the notification API from Android. There was a time where every Google I/O introduced a new API change.</p><p>Good that we have NotificationManagerCompat to save us!?</p><p>If, for example, we need to get the notification channel groups:</p><pre>val<strong> </strong>groups = <strong>notificationManagerCompat</strong>.<strong><em>notificationChannelGroups</em></strong></pre><p>We don&#39;t need to worry about the groups being supported on all OS versions, as it is handled under the hood for us:</p><pre>public List&lt;NotificationChannelGroup&gt; getNotificationChannelGroups() {<br><strong>    if (Build.VERSION.<em>SDK_INT </em>&gt;= 26) {</strong><br>        return mNotificationManager.getNotificationChannelGroups();<br>    }<br><strong>    return Collections.<em>emptyList</em>();</strong><br>}</pre><p>If we were before API level 26 we simply get an empty list, otherwise, we get the new channel groups that were introduced in 26.</p><p>You can find even more complex checks inside <a href="https://github.com/androidx/androidx/blob/androidx-main/core/core/src/main/java/androidx/core/app/NotificationManagerCompat.java#L230">NotificationManagerCompat</a>.</p><p>But if you look closer,NotificationManagerCompat will return us the actual API classes. In the example code above a list of NotificationChannelGroup, this is not a copied “compat”-version, but as of the check, safe to use:</p><pre>val groups = <strong>notificationManagerCompat</strong>.<strong><em>notificationChannelGroups</em></strong><em><br></em>val channels = groups.<em>flatMap </em>{<br><strong>    it.<em>channels</em>.<em>filter </em>{ it.shouldShowLights() }</strong><br>}</pre><p>Here we only want those groups whose channels are triggering lights, which is API level 26 and above. As we are using a class that is of higher API level than our minimum SDK, the compiler will warn us here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*WWdcZVLzzaXduUd1RT0vBg.png" /></figure><p>The compiler doesn&#39;t care that we used NotificationManagerCompat to get there.</p><p>We have multiple ways of solving this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*L_wx_xAhVMYE0SVzE7_AJw.png" /></figure><p>Adding the RequiresApi annotation to our method won’t make much sense, as we would simply move the warning to the calling function. Surrounding with a check feels obsolete as this check was already done by NotificationManagerCompat as shown above!</p><p>Seems the best option is to pick suppression:</p><pre><a href="http://twitter.com/SuppressLint"><strong>@SuppressLint</strong></a><strong>(&quot;NewApi&quot;)<br></strong>private fun checkChannels() {<br>   val groups = notificationManagerCompat.<em>notificationChannelGroups<br>   </em>val channels = groups.<em>flatMap </em>{<br>        it.<em>channels</em>.<em>filter </em>{ it.shouldShowLights() }<br>   }<br><strong>   ...<br></strong>}</pre><h3>New requirements coming in</h3><p>Let’s assume we get the additional requirement to filter out the groups that got blocked. We can add a simple check for that:</p><pre>@SuppressLint(&quot;NewApi&quot;)<br>private fun checkChannels() {<br>    val groups = notificationManager.<em>notificationChannelGroups<br>    </em>val channels =<strong> groups.<em>filterNot </em>{ it.<em>isBlocked </em>}</strong>.<em>flatMap </em>{<br>        it.<em>channels</em>.<em>filter </em>{ it.shouldShowLights()}<br>    }<br>    <strong>...<br></strong>}</pre><p>Everything looks fine, right?</p><h3>Boom!</h3><p>But we just introduced a <strong>crash</strong>! <br>The reason is: isBlocked was only introduced in API level 28 and we did not check for that! Despite we used NotificationManagerCompat, we still ran into an API level issue!</p><p>And because we suppressed theNewApi warnings, we didn&#39;t get any warning on this one!</p><p>We need to <strong>be really careful when it comes to suppression of this annotation</strong>!</p><h3>Solutions?</h3><p>As it is only available for method-level (not for individual statements), the best approach is to compose one-liner methods that can fit our needs.</p><p>Thanks to extension functions this can be very easy:</p><pre><strong>@SuppressLint(&quot;NewApi&quot;) <em>// SDK 26</em></strong><em><br></em>fun NotificationChannelGroup.lightingChannels() = <br>   <strong><em>channels</em></strong>.<em>filterLightingOnes</em>()<br><br><strong>@SuppressLint(&quot;NewApi&quot;) <em>// SDK 26</em></strong><em><br></em>private fun List&lt;NotificationChannel&gt;.filterLightingOnes() = <br>   <em>filter </em>{ it.<strong>shouldShowLights</strong>() }</pre><p>If we used this approach with the above example, we would have gotten the warning the moment we added isBlocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpkxXOXSGueoW_TyJyXw3A.png" /></figure><p>Of course, it is a bit more work for us as developers but our users will appreciate a crash-free app!</p><h3>The Linter</h3><p>The example shown was not a bug of a compat-library but rather hidden by the suppression. This could have happened with many other APIs as well.</p><p><strong>Don’t fall into this trap !<br></strong>Using Compat versions might give us false security and trick us into believing that we won’t have to think about these issues.</p><p>And again, try to <strong>avoid</strong> <strong>suppressing </strong>NewApi<strong>!</strong></p><p>Instead, use direct version checks like:</p><pre>if<strong> </strong>(Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>P</em>)</pre><p>Unfortunately, the linter is not very smart here. It would not understand slight variations like:</p><pre>.<em>filter </em><strong>{ </strong>Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>P </em><strong>}</strong></pre><h3>Call for help?</h3><p>Maybe some of you want to look more into this, with some custom lint rules. Basically, we would need something like:</p><pre>@CheckedUpTo<strong>(</strong>Build.VERSION_CODES.P<strong>)</strong></pre><p>That would internally work similar to SuppressLint(“NewApi”) but only for API calls that require nothing higher than P.</p><p>For now, make the existing linter functionality work for you. For example by also adding @RequiresApi(Build.VERSION_CODES.P) to your own code, so you are always forced to handle those.</p><p>Remember, these annotations are also considered as documentation to the reader of your code.</p><p>PS: the latest alpha of NotificationCompat will bring us compat-versions for NotificationChannel and NotificationChannelGroup 🥳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc55f16b4160" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/when-compat-libraries-do-not-save-you-dc55f16b4160">When “Compat” libraries won’t save you</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When LiveData and Kotlin don’t play  well together]]></title>
            <link>https://medium.com/google-developer-experts/when-livedata-and-kotlin-dont-play-hand-in-hand-30149aa794ec?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/30149aa794ec</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[livedata]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Tue, 15 Dec 2020 13:38:10 GMT</pubDate>
            <atom:updated>2020-12-21T15:00:41.277Z</atom:updated>
            <content:encoded><![CDATA[<h3>When LiveData and Kotlin don’t play well together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63TjCLzIvsR8aKbwKFNEkQ.jpeg" /><figcaption>Playing well together</figcaption></figure><p>The idea of LiveData was an interesting one. Based on the idea of reactive streams, that was on the peak at that time with RxJava plus adding automatic lifecycle handling — a problem on Android. LiveData had bad timing though. It arrived just before Kotlin made its impact in the Android community and sometimes both don&#39;t play that nice together. Let’s explore why and what can happen!</p><h3>The good and the bad</h3><p>The idea of LiveData was pretty simple: a lifecycle-aware implementation of the Observable pattern. In addition, if you resubscribe, you will get the last emitted value again. It could be compared to a typed version of an EventBus with sticky messages.</p><p>This is one of the core features of LiveData. But very soon after developers, including the authors, figured, you don’t always want that behavior. Let’s say you have an error value. Then you probably don’t want to show that error value again after resubscribing, like after rotation of a device — for instance.</p><p>One way to solve this is <a href="https://github.com/android/architecture-samples/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java">SingleLiveEvent</a> and it’s a good choice for one-off events like errors.</p><h3>Both worlds</h3><p>But what if you want a bit of both? You want to have the last value “sticky” plus not showing potential errors multiple times! <br>In that case, it would be good to remove our error value from LiveData after they have been consumed, right?</p><p>Let’s look at the implementation ofLiveData:</p><p>The current value is saved on a field:</p><pre>private volatile Object mData;</pre><p>Initially, it is set to NOT_SET which.</p><pre>static final Object <em>NOT_SET </em>= new Object();</pre><p>Unfortunately, is not public otherwise, we could use it to reset the value.</p><h3>What now?</h3><p>If you search for this problem, one of the most suggested solutions is simply setting it to null.</p><p>Let’s explore this:</p><pre>viewModel.results.observe(lifecycleOwner) <strong>{ </strong>result <strong>-&gt;<br>    </strong>when (result) {<br>        SomeResult.Error -&gt; {<br>            handleError()<br>            <strong>viewModel.results.<em>reset</em>()</strong><br>        }<br>        SomeResult.Result -&gt; { handleResult(result) }<br>    }<br><strong>}</strong></pre><p>where the ViewModel’s implementation is:</p><pre>class MyViewModel: ViewModel() {<br><br>    private val mutableResults = <strong>MutableLiveData&lt;SomeResult&gt;()</strong><br><br>    <strong>val results: LiveData&lt;SomeResult&gt;</strong><br>        get() = mutableResults<br><br><strong>    fun reset() {<br>        mutableResults.<em>value </em>= null<br>    }</strong><br>}</pre><p>This works, right?</p><p>Congratulations! You just introduced a crash into your code!</p><h3>But why?</h3><p>You might not even notice and might roll it out. (If so, please add unit tests next time).</p><p>The issue here is that we declared LiveData as non-nullable to the compiler!</p><p>Your observer will get notified with this null value and then immediately crash once it gets a value with a KotlinNullPointerException under the hood. There is nothing you can do anymore! It’s part of how Kotlin works!</p><p>LiveData is written in Java. It does allow setting it’s value to null. So the authors could add @Nullable annotation as we have them on other Jetpack libraries, right? No, as then you always need to handle nullable types in getValue or the Observer although you clearly might have declared your LiveData as non-null. The Generic is runtime information (for Java), annotations are compile-time information, they can’t solve this for us. And Java simply does not have null in the type system.</p><p>It’s not a bug - it’s a feature!</p><h3>How can you solve this?</h3><p>An easy one would be to mark your LiveData nullable:</p><pre>private val mutableResults = MutableLiveData&lt;<strong>SomeResult?</strong>&gt;()<br><br>    val results: LiveData&lt;<strong>SomeResult?</strong>&gt;<br>        get() = mutableResults</pre><p>Now we can handle that in the observer and only react to non null values. And more important: the compiler forces us to!</p><h3>Is there another way?</h3><p>I said earlier that we couldn’t access the original NOT_SET value. It’s not totally true. We could expose it by setting something into the jetpack package:</p><pre><strong>package androidx.lifecycle</strong><br><br>fun &lt;T&gt; LiveData&lt;T&gt;.reset(){<br><strong>    this.<em>value </em>= LiveData.<em>NOT_SET</em></strong><em> </em>as T?<br>}</pre><p>It’s a bit dirty though.</p><p>But other than that, is this actually allowed?<br>It’s at least not forbidden! Even by the newer stricter <a href="https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces">rules about private APIs</a> for apps on Google Play, it should be fine.</p><p>The actual problem is a different one, but most importantly, you rely on an implementation detail of LiveData that is not part of the public API and therefore could change anytime!</p><h3>Ok, what now?</h3><p>Another alternative is to wrap the results so you can have your own NOT_SET:</p><pre><strong>sealed class</strong> ViewModelResult {<br>    data class <strong>Result</strong>(val result: SomeResult): ViewModelResult()<br>    object <strong>NotSet</strong>: ViewModelResult()<br>}</pre><p>We would use NotSet to clear of previous values and then could just ignore that in the Observer.</p><p>It’s not the most beautiful but probably the cleanest way of solving this. <br>This is also recommended by <a href="https://medium.com/u/e0a4c9469bb5">Jose Alcérreca</a> in this <a href="https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150">article</a>.</p><h3>Anything else?</h3><p>Also, try to re-think if you need LiveData in the first place. With S<a href="https://blog.jetbrains.com/kotlin/2020/10/kotlinx-coroutines-1-4-0-introducing-stateflow-and-sharedflow/">tateFlow and </a><a href="https://blog.jetbrains.com/kotlin/2020/10/kotlinx-coroutines-1-4-0-introducing-stateflow-and-sharedflow/">ShareFlow</a> Kotlin provides a great alternative.</p><p>If you want to stick with LiveData, think if there is a way you can either have sticky or non sticky events instead of a mix?</p><p>In that case, think about updating your Linter to add a custom Lint check where our non-nullable live data cannot be set to null and the compiler in that case would cause an error.</p><p>Stay alert! This is not a LiveData issue, it could happen with other libraries too. We got very used to the Kotlin compiler warning us. But if it can’t, it might bring you into troubles you won’t even have without it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30149aa794ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-developer-experts/when-livedata-and-kotlin-dont-play-hand-in-hand-30149aa794ec">When LiveData and Kotlin don’t play  well together</a> was originally published in <a href="https://medium.com/google-developer-experts">Google Developer Experts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift’s Guard Statement for Kotlin]]></title>
            <link>https://medium.com/swlh/swifts-guard-statement-for-kotlin-967ba580443f?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/967ba580443f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 21:55:37 GMT</pubDate>
            <atom:updated>2020-12-09T03:03:21.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4asGg3EFxuVixinWc7G_A.jpeg" /><figcaption><a href="https://unsplash.com/photos/znMu0Enj_Gw">https://unsplash.com/photos/znMu0Enj_Gw</a></figcaption></figure><p>Even if you live on the Kotlin side of things maybe once in a while you also check Swift code. If you do, you probably noticed how similar both languages are. To me, Kotlin looks more concise but I’m also biased as I work with Kotlin daily. On the other hand, Swift has some great features too. One is the guard keyword, a really nice tool Swift developers have that we are missing. Can we bring it to Kotlin?</p><h3>What is guard?</h3><p>guard is used to exit a block of code early, if a given condition is not met. This way all the code following the guarded variable can be safely executed.</p><p>Let’s look at an example where we do some calculation but only if the given input can be converted into an integer:</p><pre>func printResultFor(input: String) -&gt; Void {<br>  <strong>guard</strong> <strong>let result = Int(input) else</strong> {<br>     println(&quot;input was not an integer&quot;)<br>     <strong>return</strong><br>  }<br>  // function continues with valid int<br><strong>  print(&quot;result: &quot;, 100 * result)</strong></pre><pre>}</pre><p>Of course, simple code like this could be written with the standard if/else statements! <br>But the power of guard becomes apparent when many of these statements are used in succession. Written in a traditional way this can easily lead to a hell of nested ifs where you make sure everything is safe in the innermost block when all the if are true.</p><p>Take a simple sign up flow for example, where the customer needs to enter user, password, and their age for validation. We have to make sure those are not nil or empty and check for a valid age.</p><pre>func submit(usernameText: String?, passwordText: String?, ageText: String?) {</pre><pre>  guard let username = usernameText, !username.isEmpty else {<br>      print(&quot;username is not set or blank&quot;)<br>      return<br>  }</pre><pre>  guard let password = passwordText, !password.isEmpty else {<br>      print(&quot;password is not set or blank&quot;)<br>      return<br>  }</pre><pre>  guard let ageString = ageText else {<br>      print(&quot;age is not set&quot;)<br>      return<br>  }</pre><pre>  guard let age = Int(ageString), age &gt; 18 else {<br>      print(&quot;age not valid&quot;)<br>      return<br>  }</pre><pre>  // all values are checked and valid here<br>  register(username, password, age)</pre><pre>}</pre><p>Here the register method is only called once all the criterias are met.</p><p>How would we build this with Kotlin?</p><h3>Version 1</h3><p>Let’ go back to our original simple validation and start with something like:</p><pre>fun printResultFor(input: String) {<br>    val result = input<strong>.<em>toIntOrNull</em>() ?: run</strong><em> </em><strong>{<br>       </strong><em>println</em>(&quot;input was not an integer&quot;)<br>       <strong>return</strong><br>    <strong>}<br>    <em>println</em>(&quot;result: ${100 * result}&quot;)</strong><br>}</pre><p>This is the easiest way to implement early return in Kotlin (as also shown in <a href="https://medium.com/@thecodeside/early-return-in-kotlin-a63434a246aa">this post</a>).</p><p>Actually thanks to the way every expression in Kotlin evaluates to something, we could actually implement this also with a traditional if/else:</p><pre><strong>val result</strong> = <strong>if</strong> (input.<em>toIntOrNull</em>() != null) input.<em>toInt</em>() <strong>else</strong> {<br>    <em>println</em>(&quot;input was not an integer&quot;)<br>    <strong>return</strong><br>}</pre><pre><strong><em>println</em>(&quot;result: ${100 * result}&quot;)</strong></pre><p>The compiler detects that the else case exits earlier and as of that we get a valid result variable.</p><p>Both those variants (run + if/else) work fine as long as we can return from a function.</p><h3>Is there any other way?</h3><p>How else could we get a function that shows the compile a correct type, but actually never returns? A simple (but heavy) way to achieve that is by simply throwing an exception:</p><pre>fun <strong>&lt;T&gt; shouldNotHappen</strong>(function: () -&gt; String): <strong>T</strong> {<br>    <em>println</em>(function())<br>    <strong>throw</strong> IllegalArgumentException(function())<br>}</pre><p>Now the usage can be:</p><pre>fun printResultFor(input: String) {<br>    val result = input.<em>toIntOrNull</em>() ?: <strong><em>shouldNotHappen</em></strong><em> </em><strong>{<br>        </strong>&quot;input was not an integer&quot;<br>    <strong>}<br>    </strong><em>println</em>(&quot;result: ${100 * result}&quot;)<br>}</pre><p>Maybe let’s give it a better name, how about otherwise? (unfortunately else won’t work here like in Swift).</p><pre>fun printResultFor(input: String) {<br>    val result = input.<em>toIntOrNull</em>() ?: <strong><em>otherwise</em></strong><em> </em><strong>{<br>        </strong>&quot;input was not an integer&quot;<br>    <strong>}<br>    </strong><em>println</em>(&quot;result: ${100 * result}&quot;)<br>}</pre><p>As you probably noticed, this is not the same anymore as with what we started: <br>First, it’s not clear that this block throws an exception.<br>Second, we don&#39;t want an exception to be thrown!</p><p>What we wanted, was to pass any arbitrary lambda as action when the condition is not met.</p><h3>Version 2</h3><p>We can achieve this by adding another function around it that can do the catch and the handling (we’ll mark it inline to avoid additional costs):</p><pre>fun &lt;T&gt; otherwise(function: () -&gt; Any): T {<br>    throw GuardedException(function)<br>}</pre><pre><strong>inline</strong> fun &lt;T&gt; <strong>guarded</strong>(guardedBlock: () -&gt; T) {<br><strong>    try {<br>        guardedBlock()<br>    } catch (e: GuardedException) {<br>        e.guardBroken()<br>    }</strong><br>}</pre><pre>class GuardedException(val guardBroken: () -&gt; Any) : Exception()</pre><p>Using this would look like:</p><pre>fun printResultFor(input: String) {<br>   <strong> <em>guarded </em>{<br>       </strong>val result = input.<em>toIntOrNull</em>() ?: <strong>otherwise</strong><em> </em><strong>{<br>           </strong><em>println</em>(&quot;input was not an integer&quot;)<br>       <strong>}<br>       </strong><em>println</em>(&quot;result: ${100 * result}&quot;)<br>    <strong>}<br></strong>}</pre><p>This looks nice! We are nearly there!</p><p>I think it would be nice to mark otherwise in a way that it’s clear that it will <strong>never</strong> return. Kotlin has the type Nothing for this!</p><pre>fun otherwise(function: () -&gt; Any): <strong>Nothing</strong> {<br>    throw GuardedException(function)<br>}</pre><p>Et voilà! We are done!</p><p>Check out <a href="https://gist.github.com/Aidanvii7/5c80a6008a934a95b579a307db8e19bb">this version</a> from <a href="https://medium.com/u/95a5d2c71eff">Aidan Mcwilliams</a> with who came up with this approach. You might also want to check out <a href="https://github.com/specto-dev/belay">the library</a> from <a href="https://medium.com/u/9ed6a6e02980">Nathanael</a> who uses a similar idea to find errors in his code</p><h3>A different approach</h3><p>I’d like to explore another approach though: is there a way to mark the otherwise optional without losing the safety?</p><p>It would be nice to write something like:</p><pre><strong>guarded</strong> {<br>   val result1 = <strong>guard</strong>{ input1.toIntOrNull() }<br>   val result2 = <strong>guard</strong>{ input2.toIntOrNull() }<br>   println(&quot;result: ${100 * result1 * result2}&quot;)<br>}</pre><p>Here we have two guarded blocks and we would only want the println statement when both of them succeed.</p><p>This looks nice but actually violates how guard is used in Swift:</p><blockquote>Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.</blockquote><p>But it might be handy nevertheless. We can still have the alternative block but make it optional:</p><pre><strong>guarded</strong> {<br>   val result1 = <strong>guard</strong>{ input1.toIntOrNull() }<br>   val result2 = <strong>guard</strong>(guardedBlock = { input2.toIntOrNull() }) { <br>                   <strong>println(&quot;input was not an integer&quot;) }</strong></pre><pre>   println(&quot;result: ${100 * result1 * result2}&quot;)<br>}</pre><p>To achieve this, we just need slight modification, creating a guard function with that optional 2nd parameter:</p><pre><strong>fun &lt;V&gt; guard(<br>  guardedBlock: () -&gt; V?, <br></strong> <strong> alternativeBlock: () -&gt; Any = {}</strong>): V <br>    = guardedBlock() ?: throw GuardedException(alternativeBlock)</pre><p>Wasn’t that hard, wasn’t it?</p><h3>One more modification</h3><p>Our examples have one flaw, they rely on nullability while Swifts guard handles booleans expressions. To quote the documentation:</p><blockquote>A guard statement, like an if statement, executes statements depending on the <strong>Boolean</strong> value of an expression.</blockquote><p>Achieving this is a bit more complex but we can continue on what we built above.</p><p>As we now need to return a Boolean from our function while keeping the original value, we’ll make guard an extension function of the instance itself.<br>So instead of</p><pre><strong>guarded {</strong><br>  val result1 = <strong>guard</strong>{<strong> input</strong>.toIntOrNull() }<br>  // ...<br>}</pre><p>we’ll write:</p><pre><strong>guarded {</strong><br>  val result1 = <strong>input.<em>guard</em></strong>(<strong>{ </strong><em>isNotBlank</em>() <strong>}</strong>).<em>toInt</em>()<br>  // ...<br>}</pre><p>Notice how we can call toInt safely because of the guard.</p><p>Our guard functions changed to:</p><pre>fun &lt;V&gt; <strong>V?</strong>.guard(<br>    guardedBlock: <strong>V.</strong>() -&gt; <strong>Boolean?</strong>, <br>    alternativeBlock: () -&gt; Any = {}) =<br>    i<strong>f (this != null &amp;&amp; guardedBlock(this) == true)</strong> <br>       this <strong>else </strong>throw GuardedException(alternativeBlock)</pre><p>Looks more complicated than it is. We just made it an extension function on our value. And depending on the Boolean result of the guardedBlock it returns the value itself or throws the exception as before.</p><p>With this we can write:</p><pre><em>guarded </em><strong>{<br><br></strong>    val username = usernameText.<em>guard</em>(String::isNotEmpty) <strong>{<br>        </strong><em>println</em>(&quot;username is blank&quot;)<br>    <strong>}<br>    </strong>val password = passwordText.<em>guard</em>(String::isNotEmpty) <strong>{<br>        </strong><em>println</em>(&quot;password is blank&quot;)<br>    <strong>}<br>    </strong>val ageString = ageText.<em>guard</em>(String::isNotEmpty) <strong>{<br>        </strong><em>println</em>(&quot;age is empty&quot;)<br>    <strong>}</strong></pre><pre><strong>    // ...</strong><br><strong>}</strong></pre><p>If we want we can make use of infix declaration to make this a bit nicer and also bring back the otherwise</p><pre><strong>infix fun</strong> &lt;V&gt; V?.<strong>guard</strong>(block: <strong>Pair&lt;V.() -&gt; Boolean?, () -&gt; Any&gt;</strong>) = // as before</pre><pre>infix fun &lt;V&gt; <strong>(V.() -&gt; Boolean?)</strong>.<strong>otherwise</strong>(<strong>that: () -&gt; Any</strong>)<br>                                    = <strong>this <em>to </em>that</strong></pre><p>which leads to:</p><pre><em>guarded </em><strong>{<br><br>    </strong>val username = usernameText <strong><em>guard</em></strong>(String::isNotEmpty <strong><em>otherwise</em></strong><em> </em><strong>{<br>        </strong><em>println</em>(&quot;username is blank&quot;)<br>    <strong>}</strong>)<br>    val password = passwordText <strong><em>guard</em></strong>(String::isNotEmpty <strong><em>otherwise</em></strong><em> </em><strong>{<br>        </strong><em>println</em>(&quot;password is blank&quot;)<br>    <strong>}</strong>)<br>    val ageString = ageText <strong><em>guard</em></strong>(String::isNotEmpty <strong><em>otherwise</em></strong><em> </em><strong>{<br>        </strong><em>println</em>(&quot;age is empty&quot;)<br>    <strong>}</strong>)</pre><pre><strong>    // ...</strong><br><strong>}</strong></pre><h3>Conclusion</h3><p>As you saw Kotlin as many concepts you can play with to achieve something comparable.</p><p>Of course, without an official language keyword, it’s not possible to have the same design as in Swift. But I hope I encouraged you to try to rebuild things you see in other languages and even if it’s just about practicing your own language with this.</p><p>PS: Thanks for all the reviewers that I gathered within a few minutes on <a href="https://twitter.com/PreusslerBerlin/status/1335612788941664263?s=20">Twitter</a>! You are amazing and helped me formalizing and improving these thoughts<br>PPS: Feel free to comment with even more variations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=967ba580443f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/swifts-guard-statement-for-kotlin-967ba580443f">Swift’s Guard Statement for Kotlin</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hidden pitfalls of the Elvis operator]]></title>
            <link>https://medium.com/google-developer-experts/the-hidden-pitfalls-of-the-elvis-operator-da536ba68161?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/da536ba68161</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[pitfalls]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Tue, 28 Jul 2020 08:05:18 GMT</pubDate>
            <atom:updated>2020-08-03T08:02:43.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hidden pitfalls when using Elvis operator</h3><p>I guess many of us love Elvis, both the artist and the operator in Kotlin. But it can lead to some hidden pitfalls if you are not aware of how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82D3muiY4l_HWKKWMEG58g.jpeg" /><figcaption><a href="https://unsplash.com/photos/1LCzr14Ah5U">https://unsplash.com/photos/1LCzr14Ah5U</a></figcaption></figure><p>I only realized recently when <a href="https://medium.com/u/e01d9859d7a7">Vladimir Zdravkovic</a> put some code on twitter and ask us to guess what it’s printing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8w3Ajym38XAxLGmyJ6mrAA.png" /><figcaption><a href="https://twitter.com/vlazdra/status/1287366531987406848?s=20">https://twitter.com/vlazdra/status/1287366531987406848?s=20</a></figcaption></figure><p>I assumed a hidden puzzle but I could not see the issue. I could not see any reason why this would print anything but it does! <br>After thinking about the issue (Vladimir wrote an <a href="https://dev.to/vlazdra/a-decompiled-story-of-kotlin-let-and-run-4k83">article</a> about it) I found more and more cases where this could go wrong. But let me show you some code:</p><h3>Kotlin’s null safety</h3><p>I think most of us love the way we can easily write null safe code with Kotlin like this:</p><pre>presenter?.onDestroy()</pre><p>or</p><pre>data?.let{ updateData(data) }</pre><p>And it is super easy to add an alternative case:</p><pre>data?.let{ updateData(data) } ?: run { showLoadingSpinner() }</pre><h3>Let me ask you something</h3><p>Do you think the following code is basically the same as the above?</p><pre>if (data != null) { <br>   updateData(data) <br>} else { <br>   showLoadingSpinner()<br>}</pre><p>I’m sure most of us do think they are equivalent. But what if I told you, it’s not?<br>The if/else is totally binary, it’s <strong>either-or.</strong> But with the <strong>Elvis</strong> operator, it might be <strong>both</strong>! To understand <em>why</em> we have to look closer to how it works.</p><p>Other than the else that belongs explicit to an if , the Elvis operator is not tied to a single ?. Remember, we can chain them:</p><pre>someVariable<strong>?</strong>.someField<strong>?</strong>.doSomething()</pre><p>if we now add the Elvis operator here, it will get executed depending on the expression to its left side:</p><pre>someVariable<strong>?</strong>.someField<strong>?</strong>.doSomething() ?: run { doSomethingElse() }</pre><p>so if <strong>any</strong> expression in there is null, the Elvis block will get called. It will finish evaluating <strong>everything on the left</strong> before checking if the operator is needed. This <strong>includes</strong> <strong>the last</strong> <strong>expression</strong>.</p><p>So this is depending on whatever doSomething() returns! If it is null, then the right side will be evaluated.</p><p>Or for our example:</p><pre>data?<strong>.</strong>updateData(data) ?: run { showLoadingSpinner<strong>()</strong> }</pre><p>If updateData returns null it will <strong>also</strong> show the loading spinner! This might not what you expect when thinking of it as an if/else. <br>You might think, this expression is safe but it might happen that both functions get called.</p><p>And this was what was happening in Vladimir&#39;s example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bxin_yyB_rJRTzmm3kBYmw.png" /><figcaption><a href="https://dev.to/vlazdra/a-decompiled-story-of-kotlin-let-and-run-4k83">https://dev.to/vlazdra/a-decompiled-story-of-kotlin-let-and-run-4k83</a></figcaption></figure><p>As the 2nd variable was null, it’s let was returning null and that lead to the invocation of the outer Elvis block.</p><p>So if you want the expected behavior, better do something explicitly as:</p><pre>// Extension Function to handle else cases<br>fun &lt;T&gt; T?.whenNull(block: () -&gt; Unit) = this ?: block()</pre><pre>data?.updateData(data).<strong>whenNull </strong>{ handleNull() }</pre><p>Remember, everything in Kotlin is resolving to some type including every expression. Remember, let is returning the result from your block (as does run). Stay aware! Be careful!</p><p>PS: Check out the decompiled code of the example above: <a href="https://dev.to/vlazdra/a-decompiled-story-of-kotlin-let-and-run-4k83">https://dev.to/vlazdra/a-decompiled-story-of-kotlin-let-and-run-4k83</a></p><p>PPS: Special thanks to <a href="https://medium.com/u/d8e8e655f6e4">Lucas Nobile</a> and <a href="https://medium.com/u/9fbde7d7cabf">Artur Latoszewski</a> for additional inputs here, love the wisdom of the crowd 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da536ba68161" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-developer-experts/the-hidden-pitfalls-of-the-elvis-operator-da536ba68161">The hidden pitfalls of the Elvis operator</a> was originally published in <a href="https://medium.com/google-developer-experts">Google Developer Experts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep your interfaces simple]]></title>
            <link>https://proandroiddev.com/keep-your-interfaces-simple-e025d515e3b9?source=rss-1331e67af4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e025d515e3b9</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danny Preussler]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 07:56:26 GMT</pubDate>
            <atom:updated>2020-07-20T07:50:35.870Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoiding implicit connections and learn how extension functions can help you writing good APIs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_MacXZjIgBZhmz-QKBiOg.jpeg" /><figcaption><a href="https://unsplash.com/photos/xxeAftHHq6E">https://unsplash.com/photos/xxeAftHHq6E</a></figcaption></figure><p>Writing your classes with a good API is hard but important. As the writer is trying to make it easy for the user, we sometimes tend to repeat ourselves by adding convenient methods.</p><p>Think about the List interface in Java. To check if there are no elements in the list we could check list.getLength() == 0 or we simply ask for isEmpty().</p><p>The 2nd one reads much better. But it also adds a duplication and implicit connection between the two: If the list is empty, it can’t contain any elements! This must be respected by every implementer of the interface!</p><p>We can easily think of many other methods with implicit dependencies. Think about how hashCode and equals have a connection. This is stated in the Javadocs:</p><blockquote>Note that it is generally necessary to override the hashCode method whenever equals is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.</blockquote><p>This is a pitfall that can be difficult to avoid and can lead to issues elsewhere that are difficult to track down and fix. Nowadays we have <a href="https://checkstyle.sourceforge.io/apidocs/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.html">tools</a> to validate this contract, or even better, to generate the implementation.</p><h3>Another example: feature flags</h3><p>A lot of developers work with features flags. These enable us to release continuously without the need for long-lived feature branches. Let’s say we have an interface like this:</p><pre>interface AppFeatures {<br><strong>  fun isEnabled(feature: Feature): Boolean</strong><br>}</pre><p>When using this I realized I often write code like:</p><p>if (!isEnabled(Feature.SomeFeature))</p><p>“not is enabled” does not read nicely though. But I want the reader to understand my code without thinking too much. Therefore my initial thought was to add another method to the interface</p><pre>fun isDisabled(feature: Feature): Boolean</pre><p>But I realized, doing this might break a lot of tests that simply mock the interface:</p><pre><strong>val </strong>appFeatures = <strong>mock</strong>&lt;AppFeatures&gt; <strong>{<br>    on</strong> <strong>{ isEnabled</strong>(Features.SomeFeature) <strong>} doReturn</strong> <strong>true<br>}</strong></pre><p>If I were to change the implementation to use isDisabled, the test would fail. But all I changed was an implementation detail without any actual changes. The problem with this is that, again, both methods have a hidden contract: A feature is either disabled or enabled, never both. Every implementation needs to comply, and that includes mocks, but mocks are generated implementation! Our mocking frameworks don’t know about hidden contracts we might have written (probably hidden in some JavaDoc if the contract isn’t so obvious).</p><p>This example also shows us why we should try to avoid mocking and instead use a stub implementation.</p><p>Let’s take a step back and ask ourselves if it is wise to add this method in the first place. It’s a convenient solution, but also dangerous as we can’t express the contract between two methods in the tools we have today.</p><p>Fortunately, Kotlin has some features that could help us.</p><h3>Partial solution: Default implementations</h3><p>We could add the method including its implementation directly to the interface:</p><pre>fun <strong>isDisabled</strong>(feature: Feature) = <strong>isEnabled</strong>(feature)<strong>.not()</strong></pre><p>This way the contract is fixed. The implementer just need to add isEnabled</p><p>Unfortunately, this will not work in mocking libraries like Mockito Kotlin. The reason is that in bytecode there is no actual implementation, it is still a normal Java-like interface. This means your mock is not gonna have the code of isDisabled and instead will return the default valuefalse and therefore break the contract.</p><h3>Extension functions to the rescue</h3><p>But we have another tool at our disposal. Instead of polluting our interfaces, we can move these comfort functions and still retain their usefulness. Kotlin’s extension functions are exactly about that:</p><pre>fun <strong>AppFeatures.isDisabled</strong>(feature: Feature) = <br>      <strong>isEnabled</strong>(feature)<strong>.not()</strong></pre><p>This has many advantages:</p><ul><li>It doesn’t need to be implemented by fakes or stubbed out in mocks</li><li>The interface stays simple and clean</li><li>The contract is fixed</li><li>Works with the way we want to use mocks in tests</li></ul><p>Extension functions are a very powerful tool. Many developers don’t use them to their full capabilities. So next time you define an API, remember the lesson above.</p><p>Edit: <a href="https://medium.com/u/95a5d2c71eff">Aidan Mcwilliams</a> looked into how you could even use more Kotlin features on this, continue your read <a href="https://proandroiddev.com/extension-classes-f9dcf5878b71">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e025d515e3b9" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/keep-your-interfaces-simple-e025d515e3b9">Keep your interfaces simple</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>