<?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 @sliskicode on Medium]]></title>
        <description><![CDATA[Stories by @sliskicode on Medium]]></description>
        <link>https://medium.com/@piotr.slesarew?source=rss-2a4fdbcdad17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p5wq7L0NxIPZihc0xUR8aA.png</url>
            <title>Stories by @sliskicode on Medium</title>
            <link>https://medium.com/@piotr.slesarew?source=rss-2a4fdbcdad17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 24 Sep 2026 05:34:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piotr.slesarew/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[@Preview Driven Development with Jetpack Compose]]></title>
            <link>https://medium.com/whatnot-engineering/preview-driven-development-with-compose-f7a5beee95aa?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a5beee95aa</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 16:03:39 GMT</pubDate>
            <atom:updated>2023-09-01T17:21:40.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkMlW94wCKVamWI7M6uqkQ.jpeg" /></figure><blockquote>Necessity is the mother of invention.</blockquote><blockquote>― Plato</blockquote><p>Every idea comes from a need and this time was no different. During a regular day to day feature development at Whatnot I was struggling to keep up the pace of the business. I had to implement a quite huge feature in a week, making sure that everything works as expected. But how? What corners should have been cut to deliver good quality software? Let me explain it step by step.</p><p>Firstly, let’s focus on things that I perceive as a coding pace blockers.</p><ul><li>Shame on me! Writing unit tests along with implementation of bleeding edge feature that changes every two hours not only from the business perspective but also design point of view is quite painful.</li><li>Testing complex user paths manually is frustrating and destroys focus.</li><li>Application build time. Complex codebase can slow down development pace. We all live with that pain!</li></ul><h3>🏃 Let’s skip unit testing!</h3><p>Skipping unit tests create a bad side effect of not having an ability to execute and test code in isolation. Building app every minute on device is time consuming and this is how we burn tons of development cycles. Another hidden gotcha is fixing bugs without introducing a new ones. It is almost impossible without a solid regression suite.</p><p>I decided that I can live without unit tests during feature development and write them after the product launch. At the same time I put an extra effort to make sure that the code I write is testable and clean. It is not a huge challange as our architecture builders are well established and robust. Guess what! Skipping Test Driven Development saved me tons of time! I was able to write code fast and adjust implementation without any hassle.</p><p>Unfortunately testing on device destroyed my focus and I knew that I had to do something with that. Let’s try!</p><h3>🔗‍💥 Testing on device</h3><p>Fast Android emulator, incremental compilation and build cache are definitely one of the best things that could happen to Android engineers. It is not a huge pain to run an app every couple of minutes, but what if we need to test a specific validation scenario, error states or empty paths? Those complex user paths can take some time and consume our focus. As I mentioned before, unit testing helps us with that by letting us run code in isolation, setting initial state and get fast feedback. How can we translate this approach into the world where tests simply do not exist?</p><p>To answer that question let me briefly introduce our Whatnot Android tech stack. At <a href="https://www.whatnot.com/">Whatnot</a> we are building live shopping and marketplace where you can buy, sell and discover products you will love. Along with live streaming we have plenty of seller and buyer features with rich native UI experience. We adopted Jetpack Compose at the early stage and that decision unlocked fast development cycle along with joy and developer satisfaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hzdH-Bp6Vf-E2YG25Ihcvg.png" /></figure><p>Jetpack Compose is the modern Android UI toolkit that can speed up development massively. Not only the code produced is simpler but also more elegant and concise. We do also use Jetpack ViewModel to feed our Composable UI with correct state. TL;DR MVI onboard. ViewModel is nothing else than a container that glues couple of functions that reduces state with network results and pushes it to the view layer.</p><h3>🔁⚒️ Fixing fast feedback loop</h3><p>Now when you know what tools do we use I can start explaining how I came up with a solution to fix broken feedback loop.</p><p>My goal was to build an easy solution for running UI along with model layer in isolation. On the top of that I wanted something fast, reliable and predictive. A few questions came to my mind:</p><ol><li>How to run Compose code in isolation?</li><li>How to run Model logic in isolation?</li><li>How to build a set of predefined states that I can use to test regression?</li></ol><p>First things first, running @Composable function in isolation is quite easy. Jetpack Compose comes with an additional tooling artifact that allows to render it directly in Android Studio Preview.</p><pre>debugImplementation(&quot;androidx.compose.ui:ui-tooling:VERSION&quot;)<br>implementation(&quot;androidx.compose.ui:ui-tooling-preview:VERSION&quot;)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e3c3046f1951a40bf05f0cdc3b4719e/href">https://medium.com/media/2e3c3046f1951a40bf05f0cdc3b4719e/href</a></iframe><p>This is super handy for creating a set of variants and test them in easy and fast way. Here is an example of using @Preview to visualise all secondary button states in Whatnot Design System.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hg1mAQDHKiOwlr7-qWelqQ.png" /></figure><p>Next puzzle is a bit harder. How can we use @Preview to run an entire screen or even an entire user flow in isolation? Regular screen written in Compose has more sophisticated function parameters than a button, but is that an issue? It is a challenge!</p><p>Let’s start from defining a public API of a screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbd6345aff7cc9676c4eadf4e559006f/href">https://medium.com/media/bbd6345aff7cc9676c4eadf4e559006f/href</a></iframe><p>As you can see we can run this as a regular Composable in @Preview by supplying function arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b8865538805a3d053605dff696301a9/href">https://medium.com/media/1b8865538805a3d053605dff696301a9/href</a></iframe><p>ScreenViewModel is created by hand using fake use cases. We can do even better by using another Compose tooling candy. @PreviewParameter!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2e9518aed435134ff78b5ba723feabf/href">https://medium.com/media/a2e9518aed435134ff78b5ba723feabf/href</a></iframe><p>That is nice, isn’t it? By using PreviewParameterProvider and @PreviewParameter we can define as many cases as we want. All of them will render in Android Studio Preview automatically. They follow same coding approach as JUnit test params.</p><p>So what we achieved so far? We know how to render a screen in isolation along with its model logic. That is great, but is that enough to fix broken feedback loop? Not really, as we still do not know how to use @Preview to <strong>RUN </strong>and not only <strong>RENDER </strong>complex user path.</p><p>To simplify our complex path, imagine that we have a user flow that presents a list of shipping profiles and gives an ability to add, update and delete each profile. In addition to that, every screen should handle properly empty, error and data states. We also need some advanced form validation to make sure that user knows what to do. As it happens, we have such flow in our Whatnot app so let’s use it as an example.</p><figure><img alt="Whatnot Shipping Profiles User Flow" src="https://cdn-images-1.medium.com/max/1024/1*W65xC99tex7jbJBjIcPtRw.gif" /><figcaption>Whatnot Shipping Profiles User Flow</figcaption></figure><p>As you can see, the video shows only a portion of the flow as it starts only from the Profile tab. In practice, testing every use case is more complex as we need to log in, go to the right screen, and make sure that all feature flags and configurations are set correctly. Do not be scared though. It is possible to <strong>RUN </strong>our flow in isolation using @Preview!</p><p>Going into the details it is worth mentioning that we use Compose Navigation which is nothing else than a Jetpack Navigation Component. It makes life way much easier and comes with some handy animations and tooling.</p><p>The entry point to the shipping profiles flow looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c220b2680fbc4c8b8912125b8095de8/href">https://medium.com/media/3c220b2680fbc4c8b8912125b8095de8/href</a></iframe><p>Ohh boy, that looks pretty scary at first, but let me explain what is happening here from the higher level point of view.</p><ol><li><strong>shippingProfileFlow</strong> is an extension function that can be easily connected to any nav graph. This makes flow reusable across the entire codebase.</li><li><strong>shippingProfileFlow </strong>function defines six different navigation destinations such as list, create, edit, two types of an errors and some cost optimisation info message.</li><li>The most important are the last three parameters <strong>viewModelStoreOwnerProvider</strong>, <strong>shippingProfilesViewModelProvider</strong>, <strong>shippingProfileViewModelProvider</strong>. They bring an actual “magic” that allows us to inject fake model providers and run code in isolation.</li><li>By default <strong>shippingProfilesViewModelProvider </strong>has a real implementation that injects a correct object instance based on LocalViewModelStoreOwner.current.</li><li>By default <strong>shippingProfileViewModelProvider </strong>has a real implementation that injects a correct object instance based on <strong>viewModelStoreOwnerProvider </strong>which is passed as a parameter.</li></ol><p>Such technique is nothing different than a well known Dependency Injection. Now, with all of that, we can add @Preview code and <strong>RENDER </strong>flow in isolation.</p><p>Firstly, define @PreviewParameter(s).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/677635de5ef0c11ce892e195afecb0fc/href">https://medium.com/media/677635de5ef0c11ce892e195afecb0fc/href</a></iframe><p>Then add the @Preview function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1afd4347640370a13d3ee4ce2198ef0/href">https://medium.com/media/c1afd4347640370a13d3ee4ce2198ef0/href</a></iframe><p>The most noisy part of this code is the helper functions for creating <strong>modalBottomSheetLayout</strong>, but I decided not to present it as it does not bring any real value here. Same rule apply to fake substitutions.</p><p>Finally! We are able to <strong>RENDER </strong>our flows in Android Studio Preview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKJBl3JEgZ1hWG69svPTsA.png" /></figure><p>It works! What about <strong>RUNNING</strong> them on emulator?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HY0oXRfGeDpUas-IS2lgQ.gif" /></figure><p>As you can see flows <strong>RUN</strong> in isolation and we can play with them just after less than a second. I was able to transform “static” @Preview into fully blown @Preview Driven Development tool. It speeds up code pace and allows faking different complex scenarios with just few lines of code in data provider. In addition to that, @Preview cases are great documentation and manual regression set.</p><h3>🤓 Key takeaways</h3><p>I know, that might be a lot to digest, but if you already use Compose with Jetpack ViewModel it should not be hard to apply same strategy to your codebase.</p><p>Going back to coding pace blockers.</p><ol><li>Skipping writing unit tests is not something that I would recommend, but it saves time. Actually time is not saved, but borrowed from the future! After release I wrote full unit test suite to make regression faster. It took me a day as business logic and UX was already settled.</li><li>Running complex user paths using @Preview is a game changer to me! Super easy to maintain, reliable and fast!</li><li>Incremental build time takes less than two seconds and faking through @PreviewParameter is easy and concise.</li></ol><p>To sum up, I really encourage you to start using Compose @Preview tooling if you do not. At Whatnot we are in the middle of implementing Compose Design System and I cannot imagine it without interactive @Preview(s). Stay tuned as I am planning to write about it soon!</p><p><em>If this was interesting to you, leave a comment, give some claps 👏 or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>. We are hiring at </em><a href="https://www.whatnot.com/careers"><em>Whatnot</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a5beee95aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/whatnot-engineering/preview-driven-development-with-compose-f7a5beee95aa">@Preview Driven Development with Jetpack Compose</a> was originally published in <a href="https://medium.com/whatnot-engineering">Whatnot Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Successful Live Coding]]></title>
            <link>https://proandroiddev.com/successful-live-coding-f192a7868d82?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f192a7868d82</guid>
            <category><![CDATA[public-speaking]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Sat, 07 Dec 2019 10:03:30 GMT</pubDate>
            <atom:updated>2019-12-09T13:16:14.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPIaZB51-Qtk-u4n7UP3Ww.jpeg" /></figure><blockquote>You can have all the tools in the world but if you don’t genuinely believe in yourself, it’s useless.</blockquote><blockquote>― Ken Jeong</blockquote><p>My life has many journeys and the most inspiring are those that bring me personal joy and satisfaction. Programming is one of them, and the more I am into it the more exciting it is.</p><p>I used to be pretty shy in terms of publishing my knowledge and sharing my thoughts with a broader audience. Every single public speech that I made was a disaster and a huge drama. I knew that I have to change it to evolve and push my programming skills to the max. A couple of years ago I challenged myself by deciding to become a conference speaker. In this article, I want to share with you how I overcome stress for public speeches and especially live coding. I will show you some techniques and exercises that I use to stay calm and never get surprised. Sit comfy, get your favorite beverage and enjoy reading!</p><h3>Relax, you know more than you think 🧘</h3><p>Are you familiar with the most iconic Aristotle’s quote?</p><blockquote>The more you know, the more you know you don’t know. — Aristotle</blockquote><p>That is a definition of every single engineer’s life. We learn something new every single day. Awesome, right? It would be awesome, but there is also the other side of the moon that is extremely dark😨! A lot of engineers(including myself) that I have met during my programming career were thinking that they were not good enough. Why? Because they knew a lot. They knew that there is so much knowledge out there that it is not possible to touch it all.</p><p>How is it possible that I had such a mindset? What blocked me from sharing my solutions? The answer is simple. I was too stressed about it as I only thought about what can go wrong and what things I do not know. If you want to become a speaker and successfully write code in front of the public you need to make the first step. Relax. You are doing it every day at work. Pairing with your teammates is nothing different than coding one the stage. Breath, relax and live code!</p><h3>Prepare yourself, it will reduce your stress 🤓💻</h3><p>Now when you know that being stressed can kill your motivation you need to reduce your stress during live coding itself. There are many techniques like cold showers, a small amount of alcohol or laugh therapy, but nothing can help you more than a solid preparation.</p><h4>Coding Script 📝</h4><p>Before anything else, you have to have your coding script done, as you need a clear presentation plan. To do that you do not write every single step of your coding. You also do not need to create it before you write all your code. From my experience, the best way is to sit, think twice and write all necessary building blocks(including several refactoring). After that extracting script will be way much easier. It is easier because during programming tons of things are changed and the script can be rebuilt completely. That means that spending time before coding can be a huge waste of time.</p><h4>Practice every day 👨‍💻</h4><p>Writing code can be as personal as writing poems. Many young engineers are struggling with writing code in front of the other engineers. They are scared of it as they have a too strong connection with the code they write. Other problems live in the lack of fluency and speed in typing and generating code. So how you can train to become a fearless, real time code generator?</p><p>To break a fear I recommend implementing a weekly routine to pair program with your company colleagues. A really important point is to shuffle your buddy as often as you can to get out of your comfort zone. Besides that, try to pick up bigger tasks and not just bugs or quick changes. It will give you a chance to learn and see how other people work and use their tools to get a job done. Another good exercise is MOB programming. It is an approach where the whole team works on the same thing, at the same time, in the same space, and at the same computer. So you can see it as a pairing on steroids.</p><p>Following those tips allows practicing live coding skills almost every day at work! I love pairing and I am a huge fan of extreme programming as it teaches me a lot in terms of good practices and my own weaknesses.</p><h3>Use the right tools, they will save your life ⚒️</h3><p>Now with no fear you can start building your ultimate fluency. Whenever I have to do a particular job I am looking for the best tool that I can get and I master it. I research productivity plugins and create my custom list of useful shortcuts. The most important thing is to build robust navigation awareness. Walking is not enough. You have to teach yourself how to run using your IDE. The best way is to forget about a mouse🖱️🤮, trackpad or any other pointing device. They just make you crippled.</p><p>A couple of years ago I got inspired by Hadi Hariri and his amazing talk “Mouseless Driven Development”. Since that time I treat mouse as an exception and I use only my keyboard to write code and navigate. It took quite some time to be proficient in it, but it was the best investment that I did in my life. This skill helps me a lot during live coding sessions not only during conference talks but also every day at work. Presenting solutions is easy when it can be done smoothly and without any breaking pauses.</p><p>I also released that during development there is no need to see any additional things than the code itself so I disabled icons, tabs, and other sugars. My IntelliJ IDEA looks pretty clean. Almost like an old good text editor 💪.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHqvMzxX2NqyHnZBNdoPqA.png" /></figure><p>Probably you have already seen IntelliJ in this form. It is nothing else than “Presentation Mode” except its name. It is called “Distraction Free Mode” and it can be turned on in every IntelliJ Platform-based product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5yy5kHg0Q7OHVFLsZZa-jQ.gif" /></figure><p>Programming in “Distraction Free Mode” is an awesome way to practice IDEA navigation and shortcuts. After a few months, you will be as fast as SegaSonic.</p><p>Besides that:</p><ul><li>It will make you comfortable with “Presentation Mode”.</li><li>All your coding skillset will be there for you during your live coding.</li><li>“Distraction Free Mode” is clean, neat and it makes every code presentation more readable.</li></ul><h3>TL;DR. Tips 😴</h3><p>I am so happy that you read all my thoughts but let’s have a look at tips that I gathered over a couple of years. Some of them can be implemented with minimal effort and bring instant, positive results.</p><ol><li>Believe in yourself. If you think about giving a live coding presentation that means that you know more than you think.</li><li>Prepare a coding script. Planning is important!</li><li>Practice your live coding. Use QuickTime to record your screen to see your progress.</li><li>Go deep into the implementation of the functions that you use. It will help you answer all the Q|A questions.</li><li>Pick the right tools to get a job done.</li><li>Reduce stress by being fast and fluent with your tools.</li><li>Try to implement training routines. Remember that you can practice every day at work, just do it!</li><li>During live coding avoid context switching. Try not to leave your editor at all. Use GIT and console plugins that are built into your IDE.</li><li>If you switch between two tools make sure that they are in separate desktops. Do not use just one with many windows opened as it creates a distraction.</li><li>Make sure that your desktop is empty(no icons!) and your wallpaper is minimalistic.</li><li>Turn off all your email and chat clients. Disable all system notifications if possible.</li><li>Use your daily keyboard to make you feel comfortable with the setup.</li><li>If your code depends on the external library make sure that every single one is downloaded. Try using offline mode if it is available.</li><li>Be on time. Make sure that your IDE has the best color scheme for the screen. Same story with font size. “Dark Mode” is not always the best option.</li><li>Always create backup templates of your code. It will let you finish your live coding when something will go wrong.</li><li>Have your coding script with you while presenting. Sometimes stress can make you skipping some important parts of your code. Do not let the disaster happen.</li></ol><h3>Be patient, you will get better over time 😌</h3><p>Last but not least do not get sad when your presentation will go wrong. We all make mistakes every single day and it just makes us stronger. Practice, practice, and practice more. See you on the stage!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*7UZ9YW3jmRvx7kShWHLDug.gif" /></figure><p><strong>Useful Links:</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Mob_programming">MOB programming</a></li><li><a href="https://www.agilealliance.org/glossary/xp/#q=~(infinite~false~filters~(postType~(~&#39;post~&#39;aa_book~&#39;aa_event_session~&#39;aa_experience_report~&#39;aa_glossary~&#39;aa_research_paper~&#39;aa_video)~tags~(~&#39;xp))~searchTerm~&#39;~sort~false~sortDirection~&#39;asc~page~1)">Extreme Programming</a></li><li><a href="https://www.youtube.com/watch?v=UH6YVv9js3s">Mouseless Driven Development</a></li><li><a href="https://www.jetbrains.com">IntelliJ IDEA</a></li></ul><p><em>If this was interesting to you, leave a comment, give some claps 👏 or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f192a7868d82" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/successful-live-coding-f192a7868d82">Successful Live 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[6 magic sugars that can make your Kotlin codebase happier — Part 3]]></title>
            <link>https://medium.com/@piotr.slesarew/6-magic-sugars-that-can-make-your-kotlin-codebase-happier-part-3-6319a451cd5d?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/6319a451cd5d</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Thu, 11 Jan 2018 18:01:01 GMT</pubDate>
            <atom:updated>2018-02-20T09:00:38.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OjObwJg6tJWYNht6ijvdw.jpeg" /></figure><blockquote>Don’t cry because it’s over, smile because it happened.<br>― <strong>Dr. Seuss</strong></blockquote><p>Unfortunately, all journeys have to end😿. This is the last — but not least — part of my three-part series about the sweetest Kotlin candies. In previous posts you had a chance to get familiar with:</p><ul><li>sealed classes to encapsulate different state definitions in different cases.</li><li>when() functions to permute in a clean and elegant way.</li><li>with() functions to omit qualifiers.</li><li>inline functions and reified types to write your own withCorrectType() functions with.</li></ul><p>This time I have something really special, and you can treat it as the frosting on the cake. First, I would like to introduce you to <strong>code association</strong> and how to use the delegation mechanism of the Kotlin language to make it simple and short. Then, in the second part of the article, you will become more familiar with writing your own DSL (Domain-Specific Language) structures.</p><p>Pour a cup of your favourite beverage and enjoy reading.</p><h3>KProperty: make your <strong>composition</strong> great again</h3><p>It is said that the wrong abstraction is worse than no abstraction. Actually, what this points out is that inheritance is a really tricky mechanism and it should be used carefully. Some books say that you should use composition over inheritance and that it is key to good design.</p><p>Kotlin has a built-in delegation pattern, and it is super easy to use it for <strong>aggregation.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0ba5fd26b1be3c0a0652febaad7a0f/href">https://medium.com/media/3b0ba5fd26b1be3c0a0652febaad7a0f/href</a></iframe><p>As you can see, there is no magic here. The Component class implements Navigable and Searchable interfaces and then, using the language keyword by, applies behaviours from navigable and searchable constructor parameters. This language construct is super useful as it cuts tons of boilerplate code, but it is not a silver bullet for all <strong>association</strong> scenarios.</p><p>Imagine that you need to mark your interfaces as internal because you want to make them a part of your internal architecture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eae41687f8e97727e6afedc2b1dee1f8/href">https://medium.com/media/eae41687f8e97727e6afedc2b1dee1f8/href</a></iframe><p>How does it affect the Component class? Sadly, you broke the code and now you are getting a compilation error💔. This is because the Kotlin compiler does not permit exposure of the internal components of your module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Tz71NktMqnBmIA6ZSowOXg.png" /></figure><p>So, if there is no need to expose Navigable and Searchable dependencies, you can:</p><ul><li>Remove the constructor.</li><li>Use <strong>composition </strong>instead of <strong>aggregation</strong>.</li><li>Define the ComponentInterface that contains method signatures from Navigable and Searchable interfaces.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a3918260926f7c226c27564f4244600/href">https://medium.com/media/8a3918260926f7c226c27564f4244600/href</a></iframe><p>Wow! That escalated quickly. From zero boilerplate <strong>aggregation</strong> you went to nasty-looking <strong>composition</strong>. But don’t cry, because Kotlin always has some sugar to make your codebase happier. Kotlin not only supports method delegation to the specified object using the by keyword, but also has a mechanism to delegate properties. You have probably been using it by applying the lazy() delegate to properties that should be initialised in access time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*uy5qc4_-WBtSCUN6lENHZQ.png" /></figure><p>Being lazy is good, but how is it connected with your case? It means you can apply the same pattern that is used to define the lazy() function to re-factor your <strong>composition</strong> code.</p><p>Warning! This code can change your life drastically💣.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e1447a3a3af20f329ba3044b5933926/href">https://medium.com/media/1e1447a3a3af20f329ba3044b5933926/href</a></iframe><p>ReferencedProperty is a class that takes two functions as parameters in the constructor and defines two operators.</p><ul><li>The get function takes nothing and returns a generic type T. It is an accessor function.</li><li>The set function takes a generic type T and returns Unit. It is a mutator function. Additionally, set has a default value set to empty function.</li><li>The fun getValue() operator invokes the get() function.</li><li>The fun setValue() operator invokes the set() function with a value parameter.</li></ul><p>The most important thing to know is that operators are used by the <strong>property</strong> <strong>delegation</strong> mechanism. After the ReferencedProperty class declaration, you can find two generic ref() methods that return an instance of the ReferencedProperty type. Why two? The first one will be used for properties marked as var and the second one for those marked as val.</p><p>Let’s use ref() functions to clean-up your <strong>composition</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08650219d55beeea5d7ded6677473bf2/href">https://medium.com/media/08650219d55beeea5d7ded6677473bf2/href</a></iframe><p>It looks much cleaner right now, doesn’t it? The ref() function allows you to delegate the property definition to another component. By using :: you can get KProperty0 for val and KMutableProperty0 for var. These are representations of your properties and you can easily access getter and setter functions from them. It may sound complicated but I really encourage you to play with this syntax. Hopefully, you will find it useful as it can save a lot of lines of your codebase. It saved mine! There is one caveat that you need to be aware of. This syntax uses reflection under the hood so make sure you are ready to take such trade-off.</p><p>It is about time to dive into the waters of DSL. Get ready.</p><h3>Write DSLs to cover up ugliness</h3><p>One of the coolest features of Kotlin is that it gives you the ability to write clear DSLs. A Domain-Specific Language is a computer language specialized to a particular application domain. The perfect example is a well known Anko library that was made to build the user interface of Android application programmatically. Additionally, you can use it to write statements against the SQLite database and schedule background tasks (Coroutines under the hood😎).</p><p>Not only does it simplify the code, it also makes it more readable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba2526bbe136d88cf49524d35eaeee2b/href">https://medium.com/media/ba2526bbe136d88cf49524d35eaeee2b/href</a></iframe><p>You might think that building such a pleasant API needs advanced Kotlin knowledge, but you couldn’t be more wrong! Recently, I decided to build an additional layer on the top of my acceptance tests. My main goal was to separate <strong>the WHAT</strong> from <strong>the HOW</strong>. What does that mean?</p><ul><li><strong>The WHAT</strong> should be the test itself that contains only the information that is to be tested.</li><li><strong>The HOW</strong> describes the internals of the framework that is used for testing.</li></ul><p>In addition, I wanted my test cases to look the same for Android written in Kotlin and for iOS written in Swift. Writing DSLs for those were the perfect solution.</p><p>Let’s have a look at the syntax I wanted to achieve.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21da14c221e1d60cfcb15b5b5d74c6f5/href">https://medium.com/media/21da14c221e1d60cfcb15b5b5d74c6f5/href</a></iframe><p>This is a really nice and clean looking piece of code, isn’t it? The setup() function contains prerequisites for the main test case. It makes an app to open ScreenOne using a navigation controller. Can you tell how this DSL is implemented under the hood? Of course, I am not asking about the framework that sends the commands to the target device. If you have no idea, let me explain it to you.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6bd870d29eaa972e051e497da760909/href">https://medium.com/media/a6bd870d29eaa972e051e497da760909/href</a></iframe><p>As you can see, the implementation is trivial. The navigation() function takes a block as a parameter that is nothing else but a <strong>function literal with a receiver</strong>. The body of the function invokes the block() directly on the NavController object. NavController is just an object that defines the behaviour function. This is where you implement <strong>the HOW</strong>, using any of your favourite testing frameworks.</p><p>There is one more construct living in the test case that is worth explaining.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc11b806a8e05a0e6674c0bc464f81d/href">https://medium.com/media/2bc11b806a8e05a0e6674c0bc464f81d/href</a></iframe><p>What is so interesting in the DSL mentioned above? It is almost the same as the navigation { openScreenOne() } except that after the closing bracket, there is another chained construct. How is it possible to chain such constructions? Is it a function invocation or something totally different? To make it more clear, I will change this DSL to something more obvious.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c67b0b282973f8459e79620e80bd4a82/href">https://medium.com/media/c67b0b282973f8459e79620e80bd4a82/href</a></iframe><p>The main difference is that before invoking the openSearch() function (the code shows the function using parentheses) you can see the <strong>dot notation</strong>. This shows in a very explicit way that openSearch() is a function called on some object that is returned from toolbar {}. Now it should be an easy task to implement such DSL and the implementation can look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e00cd0f1104adb3a07acbe38ceeed4a9/href">https://medium.com/media/e00cd0f1104adb3a07acbe38ceeed4a9/href</a></iframe><p>The toolbar() function looks similar to the previously implemented navigation() one. It takes the<strong> function literal with a receiver</strong> as a parameter and additionally returns an instance of the Toolbar object. It allows you to invoke the openSearch() function, which contains <strong>the HOW</strong> and returns an instance of the SearchToolbar object. Again the SearchToolbar is an object that defines the behaviour function type() that contains <strong>the HOW</strong>. Awesome!</p><p>The last riddle is the <strong>dot notation</strong> and how to achieve the DSL syntax that omits it. To be honest, the implementation is based more on a hack, than an elegant dedicated solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0b80c5e9d5f464c72516f8f71971ad/href">https://medium.com/media/5b0b80c5e9d5f464c72516f8f71971ad/href</a></iframe><p>Marking the openSearch() function as infix allows you to call it with infix notation. The infix keyword was added to the Kotlin language to answer a need for writing arithmetical and logical statements. It should not be abused to achieve other constructs. Additionally, infix can be used only for functions with one parameter. This “limitation” can cause inconsistencies in your DSL.</p><p>I hate writing endings as I feel that I am losing a friend―you. But, as I said at the beginning of this article:</p><blockquote>All journeys have to end<em>😿</em>.</blockquote><p>I hope that this three-part series has not ended but helped to start your own journey through the Kotlin language syntax. I wish you clean code and a happy codebase.</p><p><em>If this was interesting to you, please give some claps 👏 or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6319a451cd5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 magic sugars that can make your Kotlin codebase happier — Part 2]]></title>
            <link>https://medium.com/@piotr.slesarew/6-magic-sugars-that-can-make-your-kotlin-codebase-happier-part-2-843bf096fa45?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/843bf096fa45</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Fri, 08 Dec 2017 13:07:51 GMT</pubDate>
            <atom:updated>2018-01-14T17:31:16.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9ZzWZ1DU4gP793MC8CQTQ.jpeg" /></figure><blockquote>Try new things. I think a lot of what people call intelligence boils down to curiosity. — Aaron Swartz</blockquote><p>We are continuing our journey through some of my favourite Kotlin constructions. In the first part, you learned how to use sealed classes and permute two or even three enums in an elegant and concise way.</p><p>In this part, I would like to show you something that I frequently use in components that have a presentation layer. There will be also something special that perfectly demonstrates how to use an inline reified function. I hope you will appreciate my sugars the same way I do.</p><p>Let’s start with the well-known with() function.</p><h3>Use the with() function to scope invocations</h3><p>Assuming that you have never used a with() function before let’s see what you can find in the documentation:</p><blockquote>inline fun &lt;T, R&gt; with(<strong>receiver</strong>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html#T">T</a>, <strong>block</strong>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html#T">T</a>.() -&gt; <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html#R">R</a>): <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html#R">R</a> <a href="http://github.com/JetBrains/kotlin/blob/1.2.0/libraries/stdlib/src/kotlin/util/Standard.kt#L55">(source)</a></blockquote><blockquote>Calls the specified function <strong>block</strong> with the given <strong>receiver</strong> as its <strong>receiver</strong> and returns its result.</blockquote><p>😕😢😭… At first glance it looks a little complicated, but only if you have no idea what a <strong><em>block</em> </strong>or<strong> <em>receiver</em></strong> is. As always, an example will clarify them all for you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/329bd0add5902de274350b088bc9a8cd/href">https://medium.com/media/329bd0add5902de274350b088bc9a8cd/href</a></iframe><p>The first line is a no-brainer. It shows the <strong><em>receiver</em></strong> of the type String. The <strong><em>receiver</em></strong> type is important because in line three you can see a definition of the function literal with a specified <strong><em>receiver</em></strong> object. This notation may remind you of an extension function mechanism, and that is a good thing. Inside the specified <strong><em>block</em></strong>, you can call methods on the <strong><em>receiver</em></strong> object without any qualifiers. The last interesting thing is the return Unit type of the <strong><em>block</em></strong> function.</p><p>Now, <strong><em>block</em></strong> and <strong><em>receiver</em></strong> should not have any hidden logic. Using your new knowledge, applying <strong><em>block</em></strong> and <strong><em>receiver</em></strong> to the with() function is not only an easy task but also fun.</p><p>Let’s make it a little shorter, more concise and typeless.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cf99252ea80e0737b48b79d4e73547c/href">https://medium.com/media/8cf99252ea80e0737b48b79d4e73547c/href</a></iframe><p>The <strong><em>block</em></strong> lambda is the last parameter of the with() function and because of that, you can place it outside the round brackets. That is it!</p><p>So, how can you apply a with() function to your codebase to make it happier? During the last couple of months, I often used it to omit qualifiers like view.show() and view.hide() in the Presentation layer of my UI components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51fed857d076ba654498b0628f5378ec/href">https://medium.com/media/51fed857d076ba654498b0628f5378ec/href</a></iframe><p>That looks nice, doesn’t it? Moreover, it is really easy to work with such code in the future. There is no need to think about the view because our function is already scoped with it.</p><p>Now, it is time to go further and write your own withCorrectType() function using the reified keyword👊!</p><h3>Try inline reified to invoke withCorrectType()</h3><p>I truly love code reviews. In my opinion, it is one of the best ways to learn fast and exchange knowledge in your team. The next sugar is taken from my teammate’s comment to code that I refactored lately. Have you ever had the feeling that something was wrong with the codebase but you did not know how to make it better? If so, don’t feel bad because it’s completely normal.</p><p>Let’s analyse the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/580d7ae4ffb995badd811ac7a3f0d015/href">https://medium.com/media/580d7ae4ffb995badd811ac7a3f0d015/href</a></iframe><p>Can you point out any weak lines in this code? It is quite obvious that MediaItemRenderer and IconItemRenderer have similar logic in the render() method. Additionally, you can use the knowledge from the previous sugar and omit view qualifiers. Easy!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36641ccc8600b1c0c7ea925105d76106/href">https://medium.com/media/36641ccc8600b1c0c7ea925105d76106/href</a></iframe><p>Now it is time to come up with something clever. How about creating a function similar to with() and trying to move the type-checking code there?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b6fadc1b22722450ad435afb00b6ac6/href">https://medium.com/media/8b6fadc1b22722450ad435afb00b6ac6/href</a></iframe><p>Excellent! Now you are good to go and refactor your render() function, aren’t you? Hmmm… There is a small problem because your code does not compile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*PPjnUySn2ragXCvPf_BSIg.png" /></figure><p>What does it even mean that <strong>it is not possible to check for an instance of the erased type: T</strong>? This error is strictly limited to the erasure of generic types and the way generics work.</p><blockquote>During the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded. — <a href="https://docs.oracle.com/javase/tutorial/java/generics/genTypes.html">docs.oracle.com</a></blockquote><p>So, is it possible to prevent your generic T from being erased? With Kotlin, everything is possible! ...I mean, almost everything😜. By using a combination of inline and reified keywords, you can easily fix your problem.</p><p>Refactored code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b872b17013d20960b5b25d623ae2151/href">https://medium.com/media/5b872b17013d20960b5b25d623ae2151/href</a></iframe><p>You can go deeper and use the <strong>IntelliJ IDEA Kotlin Bytecode</strong> tool to find out what the Kotlin compiler did with your reified type and how the inline keyword helps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/234ade1e29219996a29fc3f96c991cab/href">https://medium.com/media/234ade1e29219996a29fc3f96c991cab/href</a></iframe><p>That is pure magic, right? The Kotlin compiler left your type because you marked it as reified. This would not be possible without marking your function using inline, as the code from withCorrentType() had to be injected directly into the invocation places.</p><p>Summing up, the inlining function with a reified type not only makes your code more readable, it also has no negative impact in terms of performance😎.</p><p>That’s all for the second part, but if you’re still hungry, stay tuned for Part 3, or return to Part 1.</p><p><a href="https://medium.com/grand-parade/6-magic-sugars-that-can-make-your-kotlin-codebase-happier-part-3-6319a451cd5d">6 magic sugars that can make your Kotlin codebase happier — Part 3</a></p><p><em>If this was interesting to you, please give some claps 👏 or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=843bf096fa45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[6 magic sugars that can make your Kotlin codebase happier — Part 1]]></title>
            <link>https://medium.com/@piotr.slesarew/6-magic-sugars-that-can-make-your-kotlin-codebase-happier-part-1-ceee3c2bc9d3?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceee3c2bc9d3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Sat, 02 Dec 2017 14:01:05 GMT</pubDate>
            <atom:updated>2017-12-21T10:54:38.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dt7r_Yp_HYm6AGLkVjrRyg.jpeg" /></figure><blockquote>Syntactic sugar causes cancer of the semicolon. — Alan J. Perlis</blockquote><p>We are constantly missing some things. Some of them are more important than the others, but it is never too late to catch up with those. Kotlin language brings tons of new concepts and features to your miserable programming life and it is really hard to use all of them in your daily duties. After almost two years of using Kotlin in production, the language itself can give me joy and satisfaction. How is it possible? Because of its many small sweet sugars 🍰.<br>In this article, I would like to share with you my favorite Kotlin candies that I discovered when I was in need of writing robust and concise components for Android applications. To make this article more friendly to read I divided it into three parts. In the first part, you will be able to see some cool features of sealed class and when() control flow function. Enjoy!</p><h3>Seal your class with a kiss of “pattern matching”</h3><p>Recently I had a chance to work with Swift. Not only did I have to review the code, I also had to translate some of the components into Kotlin. The more code I read, the more amazed I was, but the most attractive feature for me were enums 🚀. Unfortunately, Kotlin enums are not very versatile so I had to find a suitable replacement for them: <strong>Sealed classes</strong>.</p><p>Sealed classes are nothing new in the programming world. Actually, the sealed class is a pretty well-known language concept. Kotlin introduces the sealed keyword that can be added to a class declaration and used to represent restricted class hierarchies, where a value can have one type from a limited set, but cannot have any other type. Long story short, you can use sealed classes as a replacement for enums and much more.</p><p>Let’s examine the following lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4b75f93e252279147add59ebb382ceb/href">https://medium.com/media/e4b75f93e252279147add59ebb382ceb/href</a></iframe><p>At first glance, this code does nothing except declare a poor inheritance relationship, but after step by step deconstruction it shows astonishing potential. So, what actually does the sealed keyword add to the Response class? The best way to unmask it is to use the <strong>IntelliJ IDEA Kotlin Bytecode</strong> tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*zshWd4vazWpCV3zbR59bjQ.png" /><figcaption>Step 1. Reveal Kotlin Bytecode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*qu41aMbwXRNyXgXDrKE2Vw.png" /><figcaption>Step 2. Decompile Kotlin Bytecode to Java code</figcaption></figure><p>After this super easy transformation, you can start reading the Java representation of your Kotlin code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc51ffaea88d337a2433afed6681a57/href">https://medium.com/media/3fc51ffaea88d337a2433afed6681a57/href</a></iframe><p>As you have probably already guessed, sealed classes are made especially for inheritance, so they are abstract out of the box. But how are they similar to enums? Here is the moment when the Kotlin compiler does you a huge favour by allowing you to use the subclasses of the Response class as cases of the when() function. Additionally, Kotlin provides great flexibility where structures that inherit from a sealed class can be declared as data or even as an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8870678282dd3c323d087f094b353488/href">https://medium.com/media/8870678282dd3c323d087f094b353488/href</a></iframe><p>Not only does it give fully exhaustive expression, it also provides automatic casting so you can use a Response instance without any additional transformations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e67e9f2f407ae4f05ed961010676663/href">https://medium.com/media/5e67e9f2f407ae4f05ed961010676663/href</a></iframe><p>Can you imagine how ugly and complicated it could look without a sealed feature, or without Kotlin at all? If you have forgotten some of the Java language, use <strong>IntelliJ IDEA Kotlin Bytecode</strong> once again, but sit tight — it might make you faint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90b31e1ae3c630992b229c1ce12d08af/href">https://medium.com/media/90b31e1ae3c630992b229c1ce12d08af/href</a></iframe><p>Summing up, I was delighted to use the sealed keyword in such cases because it let me shape my Kotlin code in a fashion similar to the Swift version ❤️.</p><h3>Use the when() function to permute like a boss</h3><p>As you have already had a chance to see the power of when() in use with the sealed classes, I decided to share more of its robust capability with you. Imagine that you have to implement a function that accepts two enums and produces an immutable state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c4bdb337995d9d19df1dc6175e06f5/href">https://medium.com/media/12c4bdb337995d9d19df1dc6175e06f5/href</a></iframe><p>enum class Employee describes all roles that can be found in the Company XYZ and enum class Contract contains all types of an employment contract. Based on these two enums you should return a correct SafariBookAccess. Moreover, your function has to produce the state for all permutations of the given enums. As the first step, let’s prototype the signature of the state-producing function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dca0093a821e115660a9835da347137/href">https://medium.com/media/5dca0093a821e115660a9835da347137/href</a></iframe><p>Now it is time to define theSafariBooksAccess structure and because you are already aware of the sealed keyword, it is a perfect time to use it. It is not necessary to seal SafariBookAccess but it is a good way to encapsulate different state definitions in different cases of SafariBookAccess.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213a3c06514823502864f3d202f2b0e4/href">https://medium.com/media/213a3c06514823502864f3d202f2b0e4/href</a></iframe><p>So what is the main idea behind of the access() function? Permutation! Let’s permute 👊.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3ecebbeb117299202fd86239747007/href">https://medium.com/media/7d3ecebbeb117299202fd86239747007/href</a></iframe><p>This code is faultless, but can you make it more Kotlin-ish? What would you suggest while doing the day-by-day code review of your colleague’s PR/MR? Your comments can contain something like this:</p><blockquote>- Too many when() functions. Use Pair to avoid nesting.</blockquote><blockquote>- Change the order of enums parameters. Define pair as a <em>Pair&lt;Contract, Employee&gt;()</em> object to make it more readable.</blockquote><blockquote>- Merge duplicated return cases.</blockquote><blockquote>- Change to single a expression function.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50165cc52a2762bc75869fdb0fc5f619/href">https://medium.com/media/50165cc52a2762bc75869fdb0fc5f619/href</a></iframe><p>Now it looks much cleaner and more concise, but Kotlin has some additional sugar that allows you to omit the Pair definition completely 🐵. Bam!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/349e5353bbe6d5c237f02183417d7409/href">https://medium.com/media/349e5353bbe6d5c237f02183417d7409/href</a></iframe><p>I hope that you have found this useful, as this construct made my life easier and my Kotlin codebase happier. Unfortunately, it is not possible to use this syntax for triples.</p><p>That’s all for the first part, but if you’re still hungry, stay tuned for Part 2. It will be delivered shortly. Cheers!</p><p><a href="https://medium.com/grand-parade/6-magic-sugars-that-can-make-your-kotlin-codebase-happier-part-2-843bf096fa45">6 magic sugars that can make your Kotlin codebase happier — Part 2</a></p><p><em>If this was interesting to you, please give some claps 👏 or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceee3c2bc9d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Living (Android) without Kotlin]]></title>
            <link>https://medium.com/@piotr.slesarew/living-android-without-kotlin-db7391a2b170?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/db7391a2b170</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Wed, 21 Dec 2016 11:32:49 GMT</pubDate>
            <atom:updated>2016-12-24T12:25:38.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fd349rzh3XWwSbCP2IV7zA.jpeg" /></figure><blockquote>It is easier to get into something than to get out of it. — Donald Rumsfeld</blockquote><p>Living without Kotlin is like playing Warcraft III on the touchpad. Buying a mouse is simple but what can you do if your new employer does not want to let you use Kotlin in production?</p><p>There are a few options.</p><ul><li>Fight with your product owner to obtain the rights to use Kotlin.</li><li>Use Kotlin and do not tell anyone about it because you know best what is best for you.</li><li>Wipe away your tears and use Java in all its glory.</li></ul><p>Imagine that you lost the battle with your product owner and as a professional engineer, you will not lie and use hipster technology without anyone’s permission. I know that it sounds pretty scary especially when you have already tasted Kotlin but do not lose your hope.</p><p>In further parts of this article, I want to shortly describe some Kotlin features that you can apply to your Android Java code through some well-known tools and libraries. A rudimentary understanding of Kotlin and Java is required.</p><h3>Data classes</h3><p>You really do love Kotlin’s data classes, don&#39;t you? It is so easy to get equals(), hashCode(), toString() and copy() generated for you. To be specific data keyword also generates componentN() functions corresponding to the properties in their order of declaration. They are used in destructuring declarations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1558e6853f14e985f8951903ac23f4d4/href">https://medium.com/media/1558e6853f14e985f8951903ac23f4d4/href</a></iframe><p>Do you know what will be printed? For sure it will not be the value returned from the toString() of the Person class. Here is where the destructuring declaration comes to play and assigns a value from name to riddle. Using parenthesis for (riddle) compiler knows that it has to use destructuring declaration mechanism.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f3ee604248261dfb5e6cd042909965f/href">https://medium.com/media/7f3ee604248261dfb5e6cd042909965f/href</a></iframe><p>As you can see data keyword is a super useful language feature so what can you do to bring it to your Java world? Use annotation processor and modify the Abstract Syntax Tree. If you want to go deeper please read the article listed at the end(Project Lombok — Trick Explained).</p><p>Using project Lombok you can achieve almost the same functionality that data keyword provides. Unfortunately, there is no way to have destructuring declarations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c95c207f3b649acea09a14a0924645c8/href">https://medium.com/media/c95c207f3b649acea09a14a0924645c8/href</a></iframe><p>@Data annotation generates equals(), hashCode() and toString(). Additionally, it creates getters for all fields, setters for all non-final fields and constructor with all required fields(finals). It is worth to be aware of that Lombok is used just for compilation so the library code will not be added to your final .apk.</p><h3>Lambda expressions</h3><p>Android engineers have a pretty tough life because of lack of Java 8 features and one of them are lambda expressions. Lambdas are great as they cut down tons of boilerplate for you. You can use them in your callbacks and streams. In Kotlin lambda expressions are built-in and they look way much better than they look in Java. Moreover, the bytecode of the lambda can be inserted directly into the bytecode of the calling method, so the method count does not increase. It can be done using inline functions<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14f17716776683175ff6d57b3f453740/href">https://medium.com/media/14f17716776683175ff6d57b3f453740/href</a></iframe><p>Lately Google announced support for Java 8 features in Android and thanks to Jack compiler you can use lambdas in your code. It is also good to mention that they are available on API level 23 and lower.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bfc8a78e568bdd23d7ceaeb966613ca/href">https://medium.com/media/1bfc8a78e568bdd23d7ceaeb966613ca/href</a></iframe><p>How to enable them? Just add those several lines to your build.gradle file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4f70b1786a5fca1dc7ed11a07194348/href">https://medium.com/media/e4f70b1786a5fca1dc7ed11a07194348/href</a></iframe><p>If you are not a fan of Jack compiler or for some reasons you cannot use it, there is a different solution for you. Project Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7, 6 or 5 and here is the setup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680d164a574b34dfd5bd4d26029960cc/href">https://medium.com/media/680d164a574b34dfd5bd4d26029960cc/href</a></iframe><p>As I mentioned before inline functions in lambdas in Kotlin do not increase method count but what about using them with Jack or Retrolambda? Obviously, they do not come for free and the hidden costs are listed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*H7h2MB2auMslMkdaDtqAfg.png" /><figcaption>The table shows the amount of generated methods by using different versions of Retrolambda and Jack compiler. The comparison is taken from <a href="http://jakewharton.com/exploring-java-hidden-costs/">“Exploring Java Hidden Costs”</a> tech talk by <a href="https://medium.com/u/8ddd94878165">Jake Wharton</a></figcaption></figure><h3>Data manipulations</h3><p>Kotlin introduces higher-order functions as a replacement for streams. They are extremely useful when you have to transform one set of data to another or filter the collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fe946fc06c79f0bd39a97b469087a5d/href">https://medium.com/media/1fe946fc06c79f0bd39a97b469087a5d/href</a></iframe><p>Streams are also provided by Google using Jack compiler. Unfortunately, Jack does not work with Lombok because it skips generating intermediate .class files when compiling the code and Lombok depends on these files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6242429fbadf32ee79ad110d88d4a874/href">https://medium.com/media/6242429fbadf32ee79ad110d88d4a874/href</a></iframe><p>That is too good to be true so where is the catch? Sadly, streams are available from API 24. Good job Google but in what universe apps have minSdkVersion = 24?</p><p>Fortunately Android platform has an awesome open source community which produces a lot of great libraries. Lightweight-Stream-API is one of them and it contains streams implementation based on iterators for Java 7 and below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd8826fa898071c2f24b86a0a15347b3/href">https://medium.com/media/fd8826fa898071c2f24b86a0a15347b3/href</a></iframe><p>The sample above combines Lombok, Retrolambda, and Lightweight-Stream-API and it looks almost as good as Kotlin, doesn’t it. Using static factory method allows you to transform any Iterable into a stream and apply lambdas on it as on Java 8 streams. It would be perfect to wrap the static invocation Stream.of(persons) into extension function of Iterable type but Java does not support it.</p><h3>Extension functions</h3><p>Extension mechanism provides an ability to add functionality to a class without having to inherit from it. This well-known concept fits great in the Android world and that is why Kotlin is so popular in the community.</p><p>Is there any technique or magic trick that brings extension functions to your Java toolbox? Thanks to Lombok you can use them as an experimental feature. According to what Lombok documentation says they want to move it out of experimental status with no or minor changes soon. Let’s refactor last sample and wrap Stream.of(persons) into extension function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed9ce2e44feab31faeba720c4444bca3/href">https://medium.com/media/ed9ce2e44feab31faeba720c4444bca3/href</a></iframe><p>All methods that are public, static, and have at least one argument whose type is not primitive, are considered extension methods. @ExtensionMethod annotation allows you to specify a class that contains your extension functions. Instead of using one .class object you can also pass an array.</p><p>I am fully aware that some of my thoughts are pretty controversial especially Lombok ones and I also know that there are a lot of other libraries that can make your life easier. Please do not hesitate to share your experience in comments. Cheers!</p><p><a href="https://projectlombok.org/index.html">Lombok</a>, <a href="https://github.com/aNNiMON/Lightweight-Stream-API">Lightweight-Stream-API</a>, <a href="https://github.com/orfjackal/retrolambda">Retrolambda</a></p><p><a href="http://notatube.blogspot.com/2010/11/project-lombok-trick-explained.html">Project Lombok - Trick Explained</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*peB9mmElOn6xwR3eH0HXXA.png" /></figure><p><em>If this was interesting to you, please do hit the heart button ❤ or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*0B3_6GW6AKARd0BCUSiKIQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db7391a2b170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Small Things You Probably Don’t Know About Kotlin]]></title>
            <link>https://proandroiddev.com/5-small-things-you-probably-dont-know-about-kotlin-255261940de6?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/255261940de6</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Fri, 25 Nov 2016 10:35:51 GMT</pubDate>
            <atom:updated>2019-04-25T13:57:01.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6pEaY3LreZPFjvmVrz0Mw.jpeg" /></figure><blockquote>“The only true wisdom is in knowing you know nothing.” <br>― <strong>Socrates</strong></blockquote><p>I have been using Kotlin for almost a two years and I started from putting it to toy project intended for my tech talks. Do you remember that time when Kotlin had <em>traits</em> instead of <em>interfaces</em>? From the very first line, I knew that this language will change my life, and you know what? I was totally right.</p><p>Knowledge makes you better and that is why world’s most successful engineers are constantly learning new things. Here is my list of five less known things about Kotlin and I hope you will find at least three worth knowing.</p><h3>1. Name your imports</h3><p>In Kotlin, <em>imports</em> are used by the compiler to let you name your classes by their unqualified name. What happens if you have naming conflict? Sad things happen!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd67cd01014e362615c677f3702da97d/href">https://medium.com/media/bd67cd01014e362615c677f3702da97d/href</a></iframe><p>Personally, I hate using fully qualified package names in my code as it lowers readability and clarity. <strong>In Python, you can name your imports to fix the conflicts and Kotlin supports it as well</strong> ❤.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad73627008b7a9aca3a812e78da57f73/href">https://medium.com/media/ad73627008b7a9aca3a812e78da57f73/href</a></iframe><h3>2. Change companion object name</h3><p>Companion object was introduced to replace static members. It is not only for declaring static properties but also to name them. How? Let’s have a look at this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729519ad5d1b762e9ed2444d48feb596/href">https://medium.com/media/729519ad5d1b762e9ed2444d48feb596/href</a></iframe><p>By default, Kotlin creates a static nested class <em>Companion</em> for every companion object. That is why you need to use <em>CustomButton.Companion</em> to access static members from Java code(you can also use it in Kotlin but it is not necessary). <strong>Kotlin lets you change the default name of companion object to whatever name you want.</strong> Refactored code looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d55449dc3afe512e26225aad411f6d5/href">https://medium.com/media/2d55449dc3afe512e26225aad411f6d5/href</a></iframe><p>The biggest drawback is that Kotlin does not support multiple companion objects for a class. It would be great for grouping static properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d4f4c2b918cc8ba8e4413c7ac5cd9cb/href">https://medium.com/media/5d4f4c2b918cc8ba8e4413c7ac5cd9cb/href</a></iframe><h3>3. Compose functions</h3><p>I bet you used function references before but have you ever tried to use them to compose functions? Imagine that you want to map an array of prices to prices that are taxed, discounted and rounded. Using common approach you will end up with something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0667fbc6a3f172b5a401fce3b9a0ebb5/href">https://medium.com/media/0667fbc6a3f172b5a401fce3b9a0ebb5/href</a></iframe><p>This example is begging for composition so do not disregard it and make the code better place. Abracadabra!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b522e8a998d776bc89bf7c255a69a6/href">https://medium.com/media/e5b522e8a998d776bc89bf7c255a69a6/href</a></iframe><p><strong>Functions composition not only makes your code cleaner but also faster. </strong>Once you understand it, you will be able to compose almost everything.</p><h3>4. Change name of generated class</h3><p>Extension functions are one of the most attractive features in Kotlin but using them in Java code can give you a serious headache. It is ugly and besides is nothing else like invoking a static method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c5643cdb4dddd1de4db6d6d393593d6/href">https://medium.com/media/0c5643cdb4dddd1de4db6d6d393593d6/href</a></iframe><p>Kotlin generates class <em>AnyKt</em> with a static method so you can use it in Java. <strong>There is an option to change the name of generated class to achieve better readability.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5412ba6c29d8a0beb01dd9125ce5cac4/href">https://medium.com/media/5412ba6c29d8a0beb01dd9125ce5cac4/href</a></iframe><h3>5. Validate an assignment and “veto” it</h3><p>The way in which Kotlin handles delegation is pretty spectacular so if you are not familiar with it, you should totally check my article: “Zero boilerplate delegation in Kotlin”.</p><p>Besides of “class delegation”, there is an interesting mechanism called “delegated properties”<em> </em>which is used for <em>lazy</em> property initialization. How would you solve scenario in which you need to be able to intercept an assignment and “veto” it? Is there any clean way to do it? Yes, there is!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d0f0cb4ba0a99055f0970feb890aff9/href">https://medium.com/media/2d0f0cb4ba0a99055f0970feb890aff9/href</a></iframe><p>Sample shows usage of a built-in <em>vetoable</em> delegate. Lambda passed to the <em>vetoable</em> is called before the assignment of a new value to property. <strong>Returning false from the lambda allows you to “veto” the assignment but if you want to pass it through return true.</strong></p><p><a href="https://medium.com/@piotr.slesarew/zero-boilerplate-delegation-in-kotlin-e383fdef28eb">Zero boilerplate delegation in Kotlin</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkc1Y_YumE5sIffEmO03Yw.jpeg" /><figcaption><a href="http://looneytunes.wikia.com/wiki/That&#39;s_All_Folks">http://looneytunes.wikia.com/wiki/That&#39;s_All_Folks</a></figcaption></figure><p><em>If this was interesting to you, please do hit the heart button ❤ or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*0B3_6GW6AKARd0BCUSiKIQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=255261940de6" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/5-small-things-you-probably-dont-know-about-kotlin-255261940de6">Five Small Things You Probably Don’t Know About Kotlin</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[Test well, sleep well]]></title>
            <link>https://medium.com/hackernoon/test-well-sleep-well-f4ba89b0a8cc?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ba89b0a8cc</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Thu, 17 Nov 2016 10:31:24 GMT</pubDate>
            <atom:updated>2019-05-09T04:05:24.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lqgn5MJ4iaT-Zg_DoTRQLA.jpeg" /></figure><blockquote>Systems that aren’t testable aren’t verifiable. Arguably, a system that cannot be verified should never be deployed. — <strong>Robert C. Martin</strong></blockquote><p>Sleep is one of the most important and healthiest things you can do for your body. It is said that good sleepers have better concentration and productivity, isn’t that what we are all aiming for? I have been producing code for almost ten years now and I have seen and written tons of smelly, spaghetti code. Testing allows me to sleep well at night and that is why I want to share my thoughts and practices about it.</p><h4>Start writing tests</h4><p>Writing tests should be an integral part of our daily duties as you consider yourself professional software engineer. If this sounds new to you, please <strong>start testing your code</strong> <strong>from today</strong>. Trust me. I was in your boots and I know how hard is to kick off but in fact, it is easier than you think. In the beginning, you will feel a little bit disappointed because it will perturb your productivity but I can assure you that “test investment” pays off sooner than later. In addition, over time you will become more confident and a faster engineer in test.</p><h4>Treat tests like your codebase</h4><p>Almost all software engineers I have met know who is Robert C. Martin. He is a clean code evangelist and the author of amazing books and articles that changed our way of thinking about software development. Nowadays there is a lot of buzz about code refactoring, code readability, and code conciseness so why are you not applying this knowledge to your tests? People tend to draw a strong line between code and tests but for me, there is no difference and I see them as siblings. That is why <strong>I treat my tests like I treat my codebase </strong>caring about readability, conciseness, and usefulness. DRY and SOLID testing!</p><h4>Document code through tests</h4><p>Documentation is always a big pain because of hardness in maintaining it, and additionally, it is often outdated. In my opinion, the code has to be self-documented by being clear, simple, and having a full suite of tests. I always try to make my <strong>tests</strong> as <strong>readable</strong> as it is possible <strong>to provide the best documentation</strong> <strong>for my code</strong>. It is a hidden benefit of testing that every software engineer should be aware of.</p><h4>Make them fail</h4><p>If there are no failing tests every now and again, it is a sign that you are not doing them right. It is a very good practice to write tests first but this is not what I mean. <strong>Fail them to check</strong> if <strong>your</strong> setup works as incorrect mocking can make your <strong>assertions</strong> <strong>and verifications</strong> weak.</p><h4>Happy path is not enough</h4><p>The <strong>worst thing</strong> is the code covered with <strong>“happy path”</strong> tests as they give an illusory safety. Designing robust and reliable test cases is the hardest and the most satisfying part of my daily duties. To make it more interesting take your craft to extreme and use test driven development and pair program with your colleagues.</p><h4>Do not change code to write tests</h4><p>This point is crucial in conjunction with architecture and security so it should be as important as your date of birth. Think twice while breaking an encapsulation to test your code because <strong>the leaking architecture will slow down your work in the future</strong>. Actually, this kind of situations is always pointing on bad design. I made this mistake and in most cases, I ended up rewriting components from the scratch.</p><h4>Be careful with test doubles</h4><p>Simply do not misuse test doubles as they can lead to non-obvious <strong>implementation leak</strong>. When implementation details in your production code change, you will have to refactor your tests to reflect these changes. Moreover, tests will become <strong>less readable and maintainable</strong> because of huge setups.</p><h4>Review test <strong>cases</strong></h4><p>Code review is the best tool to examine pre-production code and find bugs in it. Lately, I was interviewing a couple of engineers and I noticed that their code reviewing skills were terribly neglected. Most of them do not even try to open a test class to check what is inside, scary right?</p><p>Personally, I love to <strong>review test cases</strong> and I always investigate them first. I use built-in code coverage tool in IntelliJ to check “Hits”. Too many or too little of them can tell you if the code is over or under covered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*BmHXaH-9EsDXXUXFYqt1NQ.png" /></figure><h4>Test picked up use cases</h4><p>Reading and understanding someone else’s code is our daily routine. Do you know that feeling when you have to change the non-tested code? During it you research repository, talk to other programmers, make notes and then you apply changes. There is one step missing in that chain. Before changing the code you should <strong>write the test to every single use case that you picked up</strong>. Also, you can use “characterization testing” against an existing code to understand the logic behind it.</p><h4>Try different frameworks</h4><p>It is not just that software engineers fear new <a href="https://hackernoon.com/tagged/tools">tools</a>, though they undoubtedly do. It is also that they truly believe that when you have been doing something a particular way for some time, it must be the best way to do it. I notice a strong tendency in <a href="https://hackernoon.com/tagged/java">Java</a> world to use JUnit as a main tool to write unit tests despite the fact that it has a lot of pitfalls. I use Spock in exchange for JUnit to apply robust Groovy syntax to my tests and it works like a charm. There are many <strong>other</strong>, great <strong>frameworks</strong> like TestNG and the latest Spek that <strong>can</strong> <strong>help you to achieve conciseness and readability</strong>.</p><h4>Be pragmatic</h4><p>With growing skills hunger accelerates rapidly, and to feed it you try to test everything. Remember that the more tests you write, the more code you have to maintain. <strong>Being pragmatic will stop you</strong> <strong>from testing boilerplate</strong> code such as getters, setters, constructors etc.</p><p>Summing up, I hope that you have found some helpful bits of advice or at least I inspired you enough to start working on your own best testing practices.</p><p><em>If this was interesting to you, please do hit the heart button ❤ or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*0B3_6GW6AKARd0BCUSiKIQ.gif" /></figure><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ba89b0a8cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/test-well-sleep-well-f4ba89b0a8cc">Test well, sleep well</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick dive in Kotlin extensions]]></title>
            <link>https://proandroiddev.com/quick-dive-in-kotlin-extensions-317eda4d0c0d?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/317eda4d0c0d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Sat, 05 Nov 2016 15:12:32 GMT</pubDate>
            <atom:updated>2017-08-07T19:35:51.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaZyzKXNC9LzCLzhTl2F7w.png" /><figcaption><a href="http://www.tribridge.com/blog/TribridgeConnections">http://www.tribridge.com/blog/TribridgeConnections</a></figcaption></figure><blockquote>Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. <em>— (GoF)</em></blockquote><p>As a kid, I was a fan of diving as it gave me freedom and measureless joy. Over the years my passion changed and I have started diving in deep waters of the ocean of programming. Knowing how things work brings a lot of satisfaction so let’s try to understand amazing extensions in Kotlin.</p><p>It is said that problems with architecture design are strictly connected with lack of knowledge about how language mechanisms work and what they are for. Sadly but truly nowadays countless amount of engineers have gaps in fundamentals and that is why we need to evangelize them over and over again.</p><h4>What are extensions for?</h4><p>Kotlin introduces extension functions and extension properties to solve some common scenarios. Imagine that there is a need to add or extend existing functionality to a class. What are the options?</p><ul><li>Extend an entire class</li><li>Use util function</li><li>Decorate</li></ul><p>Extending a class is always a risky option, util function will become a big static pain for testing and even using sophisticated Decorator Pattern(if applicable) generates tons of boilerplate. Kotlin extensions give the fourth and the best option you can get.</p><h4>Extend non-extendable</h4><p>Extension mechanism provides an ability to add functionality even to final classes. Let’s have a look at this code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5870e163acd9dfbefd7e2cae40f7ac61/href">https://medium.com/media/5870e163acd9dfbefd7e2cae40f7ac61/href</a></iframe><p>From the newbie perspective, it looks pretty odd. Adding functionality to String class? How is that even possible? Extensions do not actually modify classes they extend.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d990ee6aa91c60ec0c8331c90516497/href">https://medium.com/media/6d990ee6aa91c60ec0c8331c90516497/href</a></iframe><p>The sample above shows that compiler generates a class and the static function with a receiver as a parameter. The receiver has a type of extended class. Now it is obvious why the code is so awful when extension functions are used in Java. In the end, they are only static functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30ea2ca159b8ba4821b81039dfdb0a43/href">https://medium.com/media/30ea2ca159b8ba4821b81039dfdb0a43/href</a></iframe><h4>Inlining matters</h4><p>Inline functions are extremely beneficial in case of a having function that takes functions as parameters. That sounds like an inception but do not be frightened. It is just a functional programming and it is closely related to extension functions.</p><p>Lately, I was dealing a lot with collections and for most of the time, I had to search through them in reverse order. My pre-refactored code looked like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20197bdee3023ae0eda608012be94fc1/href">https://medium.com/media/20197bdee3023ae0eda608012be94fc1/href</a></iframe><p>As soon as I typed .<em>reversed().forEach() </em>twenty<em> </em>times I realized that it is a really good idea to squash it into .<em>reversedForEach(). R</em>efactored code used extension function which I added to <em>Iterable</em> type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c7aa0ba6e5c3d0f59efc9922d4e285/href">https://medium.com/media/37c7aa0ba6e5c3d0f59efc9922d4e285/href</a></iframe><p>Everything was great except a performance. I accidentally forgot to <em>inline</em> my function so my code was creating redundant objects. This is a common mistake in designing extension functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Wsah0hFTzI4-a0MYBgOoA.png" /><figcaption><strong>Left:</strong> no inlining |<strong> Right:</strong> with inlining</figcaption></figure><p>The picture shows Java code generated from Kotlin. It is clear that <em>inlining</em> has a great impact on bytecode. For the closer look, I suggest to read carefully <em>inline functions</em> section in Kotlin reference and play with some samples.</p><p>Summing up extension functions have a great potential to cure a lot of headaches but it needs to be remembered that with a great power comes a great responsibility so use them consciously.</p><p><em>If this was interesting to you, please do hit the heart button ❤ or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*0B3_6GW6AKARd0BCUSiKIQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=317eda4d0c0d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/quick-dive-in-kotlin-extensions-317eda4d0c0d">Quick dive in Kotlin extensions</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[Zero boilerplate delegation in Kotlin]]></title>
            <link>https://proandroiddev.com/zero-boilerplate-delegation-in-kotlin-e383fdef28eb?source=rss-2a4fdbcdad17------2</link>
            <guid isPermaLink="false">https://medium.com/p/e383fdef28eb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jetbrains]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[@sliskicode]]></dc:creator>
            <pubDate>Fri, 28 Oct 2016 14:51:55 GMT</pubDate>
            <atom:updated>2017-11-06T22:22:36.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyOos_uZ4-uhl2-F8h5kkQ.jpeg" /></figure><blockquote>Delegation is an implementation mechanism in which an object forwards or delegates a request to another object. — <em>(GoF)</em></blockquote><p>It is said that inheritance is useful only in case of having Donald Trump as a father. Abstract classes have a lot of gotchas in term of designing scalable and reusable architecture. How many times did you create the superclass in your codebase that could not be replaced and blocked you from doing new fancy features? Thanks to Henry Lieberman our programming toolbox include an amazing delegation<em>, </em>so it can be used against wrong abstractions. Remember! The wrong abstraction is worse than no abstraction.</p><p>Words are cheap, let’s compose a <strong>CopyPrinter</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7314651ece05151749ade66d2c3e0a91/href">https://medium.com/media/7314651ece05151749ade66d2c3e0a91/href</a></iframe><p>The sample above is pretty straightforward, but still begging for some code generation because of having boilerplate in it. It would be so nice to have delegation as a built-in language feature. In old Java world things like that does not exist, so is there any way to solve that problem differently? It is possible to use annotation processing to create a library for code generation or implement reflection to invoke methods dynamically. That sounds pretty scary, right? As a fan of Kotlin, I will show you how to delegate like a pro.</p><h3>Kotlin</h3><p>As I have already mentioned, there is a huge need of having delegation<strong> </strong>pattern implemented in language. Guess what! Kotlin has it❤.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6450aee43f9d358c30de8fa1cd01a199/href">https://medium.com/media/6450aee43f9d358c30de8fa1cd01a199/href</a></iframe><p>Kotlin delegation mechanism squashes 30 lines of Java code in just 11. When I saw it for the first time it literally blew my mind. Kotlin makes it so clear and concise that there is no need for explanation. However, nothing is for free and there is no magic behind it. As an engineer, I always dig deeper to fully feed my appetite and see how things work internally.</p><p>The easiest way to understand how Delegates work is by using IntelliJ IDEA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*vS6Rh2HLrPUb9rpbLWgTNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*U-1dOuNYllnIipstRtg_jQ.png" /></figure><p>IntelliJ IDEA comes with bundled Kotlin decompiler so you can explore generated bytecode and translate it to Java. By doing it on our sample you are able to see such a beauty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8212252b0b288b86da5965935277d59/href">https://medium.com/media/b8212252b0b288b86da5965935277d59/href</a></iframe><p>I intentionally deleted imports and metadata to improve readability, so now it can be seen that everything is generated and no dark magic is involved in Delegates.</p><p>And if that is not enough, Kotlin have the whole concept of Delegated Properties. If you are not familiar with it, you should read about it and start using as soon as possible.</p><blockquote>Any piece of code that you’re forced to duplicate or that can be automatically generated by an IDE is a missing language abstraction feature. — (<a href="https://twitter.com/mariofusco/status/790171082242359296">Mario Fusco</a>)</blockquote><p><em>If this was interesting to you, please do hit the heart button ❤ or </em><a href="https://twitter.com/SliskiCode"><em>let me know on Twitter</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*0B3_6GW6AKARd0BCUSiKIQ.gif" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff20c9a%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Ff20c9a%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252Ff20c9a%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c27c6bd6c8dea21c9726d9564b27d6/href">https://medium.com/media/87c27c6bd6c8dea21c9726d9564b27d6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e383fdef28eb" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/zero-boilerplate-delegation-in-kotlin-e383fdef28eb">Zero boilerplate delegation in Kotlin</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>