<?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 Fanis Veizis on Medium]]></title>
        <description><![CDATA[Stories by Fanis Veizis on Medium]]></description>
        <link>https://medium.com/@fanisveizis?source=rss-38367c2ec35c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CovBTujOV2nEqTFrw3uhZw.jpeg</url>
            <title>Stories by Fanis Veizis on Medium</title>
            <link>https://medium.com/@fanisveizis?source=rss-38367c2ec35c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fanisveizis/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[SOLID principles, in 5 words or less]]></title>
            <link>https://medium.com/@fanisveizis/solid-principles-in-5-words-or-less-291453cf534f?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/291453cf534f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[good-practices]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Sat, 22 Aug 2020 12:21:26 GMT</pubDate>
            <atom:updated>2020-08-22T12:21:26.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKbOog1ANsio8qHeNRqzCg.jpeg" /></figure><p>The SOLID mnemonic acronym is a collection of five code design principles aimed at guiding developers to write more understandable, flexible, maintainable and overall higher quality code. They are a subset of a larger group of principles introduced in Robert C. Martin’s body of work and they form a core philosophy applicable in, among others, agile and adaptive software development.</p><p>Although the word SOLID is an acronym, and, by definition is meant to be memorable and easy to recall, the names of the principles themselves may not be self-explanatory. So, 5 principles, lets summarise them in 5 words, or less.</p><h4>S is for the Single Responsibility principle</h4><p>In 5 words or less</p><blockquote>Only do the Right thing</blockquote><p>In a few more words, this principle can be defined as <em>gathering together the things that change for the same reasons; separating those things that change for different reasons</em>.<br>What that means is that a class (or module or however/whatever one defines as a concrete chunk of code) should be responsible for one thing and one thing only. That in turn leads to having a singular reason to change and being unaffected from changes and updates to code that are logically far away.</p><h4>O is for the Open-Closed principle</h4><p>In 5 words or less</p><blockquote>Allow extension not Modification</blockquote><p>In a few more words, this principle states that <em>software entities should be open to extension and at the same time closed to modification</em>, thus allowing for features to be enhanced without going back and refactoring things.<br>This might sounds hard and confusing but at the same time it is one of the core building blocks of agile engineering, with Robert C. Martin calling it the most important principle of object-oriented design. Although there are many ways to accomplish this, it might help keeping in mind that every long if or switch statement is an opportunity for further abstraction.</p><h4>L is for the Liskov Substitution principle</h4><p>In 5 words or less</p><blockquote>Children should mimic their Parents</blockquote><p>In a few more words, this principle states that <em>we should design our code in such a way that we can easily swap a Superclass for a Subclass without altering the expected behaviour and without causing any unexpected side effects</em>. Correctness should always be unaffected.<br>In other words, if a child class cannot/does not act like the parent class in the same scenarios, most likely they should not inherit from this particular parent class.</p><h4>I is for the Interface Segregation principle</h4><p>In 5 words or less</p><blockquote>Keep Interfaces lean</blockquote><p>In a few more words, according to this principle, <em>many client-specific interfaces are better than one general-purpose interface</em>.<br>As such, we shouldn’t have long generic interfaces which in turn would lead to even longer and bulkier implementations of those, leaving us with a guaranteed way of having either empty method bodies or wrongly exposed functionality.</p><h4>D is for the Dependency Inversion principle,</h4><p>In 5 words or less</p><blockquote>Always depend on Abstractions</blockquote><p>In a few more words, following this principle, <em>both high level and low level entities should depend on abstractions instead of concrete implementations</em>.<br>In doing so, every piece of code, regardless of what it does, how complex or simple it is or how many dependencies it has, it should only be exposed to abstractions to promote louse coupling, flexibility, interoperability and testability.</p><p>That was the SOLID principles in a way that will, hopefully, stick and be easier to remember. Would you summarise them in a different way?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=291453cf534f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kode Quality: Single Responsibility]]></title>
            <link>https://medium.com/@fanisveizis/kode-quality-single-responsibility-9fb9599fd4e2?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fb9599fd4e2</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[superman]]></category>
            <category><![CDATA[code-quality]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 20:13:46 GMT</pubDate>
            <atom:updated>2020-08-11T20:13:46.956Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the first in a series of articles focusing on interpreting and implementing popular Code Quality principles with Kotlin. The series is called <em>Kode Quality</em> because for one, using <strong>K</strong> for Kotlin stuff is still cool, and second, because <em>Kode Kwality</em> felt like too much… What? The K stuff is not cool? It never was? Ugh, whatever…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPRuszcUBF9_dJc8P2jVVw.jpeg" /></figure><p>The Single Responsibility Principle is the big S in the SOLID mnemonic acronym, a collection of five code design principles aimed at guiding developers to write more understandable, flexible, maintainable and overall higher quality code. In the words of Robert C. Martin, it can be defined as:</p><blockquote>Gathering together the things that change for the same reasons; separating those things that change for different reasons.</blockquote><p>What that means is that a class (or module or however/whatever one defines as a concrete chunk of code) should be responsible for one thing and one thing only. That in turn leads to having a singular reason to change and being unaffected from changes and updates to code that are logically far away.</p><p>Simpler still, following the single responsibility principle, no piece of code should do too much. To paraphrase Paul McCartney, anytime you feel the pain, hey dude, refrain, don’t carry the world upon your shoulders.</p><p>~</p><p>How can Kotlin help with following the Single Responsibility Principle?</p><h4>Delegation</h4><p>Let’s take the Man of Steel as an example, the person who literally does too much:</p><pre>class Superman {<br>    fun fly() { /* ... */ }<br>    fun shootLasers() { /* ... */ }<br>    fun stopBullets() { /* ... */ }<br>}</pre><p>He can do so much more, but in code-land, those three tasks are a handful already. We can improve this class simply by creating interfaces and grouping things appropriately, but with Kotlin and delegation we can take it a step further and turn Kal El into, essentially, Tony Stark.</p><pre>interface Flying {<br>    fun fly()<br>}<br><br>interface Attacking {<br>    fun shootLasers()<br>}<br><br>interface Defending {<br>    fun stopBullets()<br>}<br><br>class IronMan(<br>    private val flightModule: Flying,<br>    private val attackModule: Attacking,<br>    private val defenceModule: Defending<br>) : Flying by flightModule, Attacking by attackModule, Defending by defenceModule</pre><p>In our case, IronMan can do everything Superman can do but his only actual responsibility is to delegate to the implementations of the interfaces.</p><h4>Data Classes</h4><p>Continuing with Superman, let’s delve into his public and private identity dilemma:</p><pre>class Superman(<br>    private val secretFirstName: String, <br>    private val secretLastName: String,<br>    val firstName: String, <br>    val lastName: String<br>) {<br>    private fun secretIntro() { <em>print</em>(&quot;Hey, I&#39;m $secretFirstName $secretLastName&quot;) }<br><br>    fun intro() { <em>print</em>(&quot;Hey, I&#39;m $firstName $lastName&quot;) }<br>}</pre><p>Grouping his credentials into a data class, can help with having less repetition, less spread of data and code and an overall cleaner outcome.</p><pre>data class Credentials(<br>    val firstName: String,<br>    val lastName: String)<br>{<br>    fun intro() { <em>print</em>(&quot;Hey, I&#39;m $firstName $lastName&quot;) }<br>}<br><br>class Superman(<br>    private val secretId: Credentials,<br>    val id: Credentials<br>)</pre><h4>Inline Classes</h4><p>If you hate representing everything as Strings, go for Inline classes.</p><pre>inline class Name(val value: String)<br><br>data class Credentials(<br>    val firstName: Name,<br>    val lastName: Name)<br>{<br>    fun intro() { <em>print</em>(&quot;Hey, I&#39;m $firstName $lastName&quot;) }<br>}</pre><h4>Extensions</h4><p>If you hate having anything except properties in Data Classes, go for extension functions.</p><pre>data class Credentials(<br>    val firstName: Name,<br>    val lastName: Name<br>)<br><br>fun Credentials.intro() { <em>print</em>(&quot;Hey, I&#39;m $firstName $lastName&quot;) }</pre><p>With extension functions you get the benefit of having (for lack of a better word) physical separation of responsibilities while still maintaining the illusion of functionality being grouped together.</p><p>You also get the added bonus of being able to separate primary and secondary responsibilities by only having the former as part of the actual Class/Entity and having the latter as extensions.</p><p>~</p><p>This has been a few ways that I have personally found neat and helpful in implementing the Single Responsibility Principle with Kotlin. Do you have any more Kotlin tricks to share that would be helpful in achieving Single Responsibility?</p><p>Thank you for reading and stay tuned for more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fb9599fd4e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boilerplate free proxy fakes]]></title>
            <link>https://medium.com/@fanisveizis/boilerplate-free-proxy-fakes-ec0f09ce6957?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0f09ce6957</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 20:44:53 GMT</pubDate>
            <atom:updated>2020-04-04T20:44:53.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWZPYRXs7PKXVwiuMwR-Hg.jpeg" /></figure><p>With the fake vs mock argument heating up lately, many have been taking the side of fakes. But there is one thing that never seems to be addressed; the boilerplate code we most likely need to live with when creating and maintaining fake instances of entities.</p><p>If only there was a way to create fakes and only implement what actually is needed and ignore everything else.</p><blockquote>Enter, the Java Proxy.</blockquote><p>A Java Proxy Instance is an object of an interface that will forward invocations to an Invocation Handler. Whenever an invocation occurs on the proxy, the proxy instance itself, the method and the arguments of the invocation will be passed to the Invocation Handler that was used to create the proxy.</p><p>It only works with interfaces, but we are supposed to be depending on abstractions anyway, so maybe that limitation is a good thing.</p><p>To use an Invocation Handler, we must create a new class and implement the InvocationHandler interface which will in turn require the implementation of the invoke method. As stated above, the invoke method accepts the proxy itself, the method and the arguments of any invocation on the proxy.</p><p>To create a Proxy, we need a Class Loader instance, the Type that will be proxied and an instance of an InvocationHandler implementation, passing all those to the Proxy.newProxyInstance factory.</p><blockquote>Neat, but how does it help with fakes?</blockquote><p>Well, think of it this way: what if hidden behind a proxy, was another object that mimics the interface we wanna fake but only “implements” what we care about. The word mimics and the quotes were chosen on purpose as this object would just have methods that match the signature of the methods that we need and doesn’t <em>really</em> implement anything.</p><p>Like they say, a code sample is worth a thousand words and Kotlin &gt; * so here comes. A simple interface:</p><pre>interface SimpleInterface {<br>    fun noise1()<br>    fun noise2()<br>    fun interesting1()<br>    fun interesting2(a: Int, b: Int): Int<br>}</pre><p>We don’t need the noise, just the juicy stuff so here’s the anonymous class instance that mimics this interface:</p><pre>val <em>mimic </em>= object {<br>    fun interesting1() = <em>println</em>(&quot;Hello world!&quot;)<br>    fun interesting2(a: Int, b: Int) = a + b<br>}</pre><p>But how do we combine the two to turn the mimic into a fake SimpleInterface?</p><p>Let’s start with a new InvocationHandler implementation:</p><pre>class FakeHandler : InvocationHandler {<br>    override fun invoke(<br>        proxy: Any, <br>        method: Method, <br>        args: Array&lt;out Any&gt;?): Any? {}<br>}</pre><p>We will use the arguments of the invoke method to find an identical signature in the mimic instance. So first we need that mimic instance referred in the InvocationHandler, so:</p><pre>class FakeHandler(<strong>private val mimic: Any</strong>) : InvocationHandler {<br>    override fun invoke(<br>        proxy: Any,<br>        method: Method,<br>        args: Array&lt;out Any&gt;?): Any? {}<br>}</pre><p>Next we need to fetch this mimicked override from the mimic:</p><pre>class FakeHandler(private val mimic: Any) : InvocationHandler {<br><br>    <strong>private fun getOverride(<br>        name: String,<br>        params: Array&lt;Class&lt;*&gt;&gt;?): Method? {</strong><br><br>        val type = mimic::class.<em>java<br>        </em>return try {<br>            if (!params.<em>isNullOrEmpty</em>()) {<br>                type.getMethod(name, *params)<br>            } else {<br>                type.getMethod(name)<br>            }<br>        } catch (_: Exception) {<br>            null<br>        }<br>    <strong>}</strong><br><br>    override fun invoke(<br>        proxy: Any,<br>        method: Method,<br>        args: Array&lt;out Any&gt;?): Any? {<br><br>        <strong>val override = getOverride(<br>            method.<em>name</em>, <br>            method.<em>parameterTypes</em>)</strong><br>    }<br>}</pre><p>Now, if we actually found a mimicked implementation, let’s invoke it, otherwise let’s just move on:</p><pre>class FakeHandler(private val mimic: Any) : InvocationHandler {<br><br>    private fun getOverride(<br>        name: String,<br>        params: Array&lt;Class&lt;*&gt;&gt;?): Method? {<br><br>        val type = mimic::class.<em>java<br>        </em>return try {<br>            if (!params.<em>isNullOrEmpty</em>()) {<br>                type.getMethod(name, *params)<br>            } else {<br>                type.getMethod(name)<br>            }<br>        } catch (_: Exception) {<br>            null<br>        }<br>    }<br><br>    override fun invoke(<br>        proxy: Any,<br>        method: Method,<br>        args: Array&lt;out Any&gt;?): Any? {<br><br>        val override = getOverride(<br>            method.<em>name</em>,<br>            method.<em>parameterTypes</em>)<br><br>        <strong>return if (override != null) {<br>            if (args != null) {<br>                override.invoke(mimic, *args)<br>            } else {<br>                override.invoke(mimic)<br>            }<br>        } else {<br>            null<br>        }</strong><br>    }<br>}</pre><p>Now, this will throw an exception that won’t make much sense if we try to invoke a method that has not been implemented but which returns a value. Let’s remedy that:</p><pre>class FakeHandler(private val mimic: Any) : InvocationHandler {<br><br>    private fun getOverride(<br>        name: String,<br>        params: Array&lt;Class&lt;*&gt;&gt;?): Method? {<br><br>        val type = mimic::class.<em>java<br>        </em>return try {<br>            if (!params.<em>isNullOrEmpty</em>()) {<br>                type.getMethod(name, *params)<br>            } else {<br>                type.getMethod(name)<br>            }<br>        } catch (_: Exception) {<br>            null<br>        }<br>    }<br><br>    override fun invoke(<br>        proxy: Any,<br>        method: Method,<br>        args: Array&lt;out Any&gt;?): Any? {<br><br>        val override = getOverride(<br>            method.<em>name</em>,<br>            method.<em>parameterTypes</em>)<br><br>        return if (override != null) {<br>            if (args != null) {<br>                override.invoke(mimic, *args)<br>            } else {<br>                override.invoke(mimic)<br>            }<br>        } <strong>else if (method.<em>returnType </em>!= Void.<em>TYPE</em>) {<br>            throw IllegalStateException(<br>                &quot;Invoked a non-faked method (\&quot;${method.<em>name</em>}\&quot;) &quot; +<br>                   &quot;with a return type (\&quot;${method.<em>returnType</em>}\&quot;).&quot;)<br>        }</strong> else {<br>            null<br>        }<br>    }<br>}</pre><p>Let’s add some sprinkles by creating a neat top-level function that creates the fake with the enclosed handler and mimic instance:</p><pre>@Suppress(&quot;UNCHECKED_CAST&quot;)<br>fun &lt;T : Any&gt; fakeIt(type: Class&lt;T&gt;, overrides: Any): T {<br>    return Proxy.newProxyInstance(<br>        ClassLoader.getSystemClassLoader(),<br>        <em>arrayOf</em>(type),<br>        FakeHandler(overrides)<br>    ) as T<br>}</pre><p>Let’s use it:</p><pre>val <em>fake </em>= <em>fakeIt</em>(SimpleInterface::class.<em>java</em>, object {<br>    fun interesting1() = <em>println</em>(&quot;Hello world!&quot;)<br>    fun interesting2(a: Int, b: Int) = a + b<br>})</pre><p>Stay safe, cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0f09ce6957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contextual Overriding with Kotlin]]></title>
            <link>https://medium.com/@fanisveizis/contextual-overriding-with-kotlin-dc33e9824bef?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc33e9824bef</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 22:54:02 GMT</pubDate>
            <atom:updated>2020-02-13T22:54:02.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*HT-ddwKpKVdSnDcDYRU8ig.jpeg" /></figure><p>You have one abstract class or interface with two unimplemented functions functionOne and functionTwo. You want, whoever implements those two functions, to have access to different resources.</p><p>In the functionOne implementation, you want to permit access to propertyOne and functionOne, while in the functionTwo implementation, you want to permit access to propertyTwo and functionTwo.</p><h4>Two different contexts, one class to extend. Can you do it? With Kotlin, sure.</h4><p>Separate your resources.</p><pre>sealed class ContextOne {<br>    val propertyOne = &quot;One&quot;<br>    fun funOne() {}<br>}<br><br>sealed class ContextTwo {<br>    val propertyTwo = &quot;Two&quot;<br>    fun funTwo() {}<br>}</pre><p>Use them as unimplemented extension functions.</p><pre>interface ToOverride {<br>    fun ContextOne.overrideOne()<br>    fun ContextTwo.overrideTwo()<br>}</pre><p>Implement.</p><pre>class Overriding : ToOverride {<br>    override fun ContextOne.overrideOne() {<br>        propertyOne<br>        funOne()<br>    }<br><br>    override fun ContextTwo.overrideTwo() {<br>        propertyTwo<br>        funTwo()<br>    }<br>}</pre><p>propertyTwo and funTwo cannot be accessed from overrideOne and vice verse. Useful? Maybe. Cool? Definitely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc33e9824bef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Given When Then, but Why and How?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@fanisveizis/given-when-then-but-why-and-how-8464dafc372c?source=rss-38367c2ec35c------2"><img src="https://cdn-images-1.medium.com/max/1919/1*vJe2ssCq9rTLZBEzoKPeug.png" width="1919"></a></p><p class="medium-feed-snippet">A few good practices on using our favourite test structure formula</p><p class="medium-feed-link"><a href="https://medium.com/@fanisveizis/given-when-then-but-why-and-how-8464dafc372c?source=rss-38367c2ec35c------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@fanisveizis/given-when-then-but-why-and-how-8464dafc372c?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8464dafc372c</guid>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Sat, 30 Nov 2019 11:18:33 GMT</pubDate>
            <atom:updated>2019-11-30T11:18:33.291Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[If you’re Kotling, start Moshing. (aka cleaning the data layer with Kotlin & Moshi)]]></title>
            <link>https://medium.com/@fanisveizis/if-youre-kotling-start-moshing-aka-cleaning-the-data-layer-with-kotlin-moshi-e966ff163922?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e966ff163922</guid>
            <category><![CDATA[moshi]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Sat, 26 Jan 2019 04:06:29 GMT</pubDate>
            <atom:updated>2019-01-26T04:06:29.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ztE9cBi163twEtPaK7mjw.jpeg" /></figure><h3>Introduction</h3><h4>OK, so why Moshi?</h4><p>With so many Json parsing projects out there, what sets Moshi apart? Well, there are many favorable arguments, both from novice users and established authorities. Instead of rehashing and repeating, here’s some good reading material on the subject.</p><ul><li><a href="https://www.reddit.com/r/androiddev/comments/684flw/why_use_moshi_over_gson/">Why use Moshi over Gson?</a></li><li><a href="https://medium.com/@BladeCoder/advanced-json-parsing-techniques-using-moshi-and-kotlin-daf56a7b963d">Advanced JSON parsing techniques with Moshi</a></li><li><a href="https://www.reddit.com/r/androiddev/comments/8e0r2b/choosing_json_library_in_2018/">Choose JSON library in 2018</a></li></ul><h4>OK, but why combine Kotlin with Moshi?</h4><p>Since the release of v1.5.0, Moshi added full support for Kotlin and Kotlin types with reflection, and since v1.6.0, the same functionality was extended to code generation with annotation processing.</p><p>No matter which path you choose to take, Moshi goes hand in hand with Kotlin and respects the language’s features along with the rules defined by the developer. Here’s some <em>more</em> good reading material.</p><ul><li><a href="https://medium.com/@ZacSweers/exploring-moshis-kotlin-code-gen-dec09d72de5e">Exploring Moshi’s Kotlin code gen</a></li><li><a href="https://engineering.kitchenstories.io/data-classes-and-parsing-json-a-story-about-converting-models-to-kotlin-caf8a599df9e">Data classes and parsing JSON</a></li><li><a href="https://www.reddit.com/r/androiddev/comments/8jjms9/moshi_16_released_with_support_for_code/">Moshi 1.6 release with support for Kotlin types</a></li><li><a href="https://medium.com/square-corner-blog/kotlins-a-great-language-for-json-fcd6ef99256b">Kotlin’s a great language for JSON</a></li></ul><h4>OK, so is that it?</h4><p>Actually no. I was aware of all the above but never actually saw the need to switch from Gson. But the straw that broke the camel’s back was when I started getting exceptions about null values on properties I had defined as non-nullable.<br>And it was then that I realised that Gson was completely ignoring both the null safety I had defined as well as all the default values. <a href="https://proandroiddev.com/most-elegant-way-of-using-gson-kotlin-with-default-values-and-null-safety-b6216ac5328c">Here</a>, you can read about the issue, and <a href="https://github.com/square/moshi/issues/331">here</a>, you can see that it is something dealt with by Moshi.</p><p>So I switched to Moshi and my Json parsing remained just as simple as with Gson. Only now it became something even more important; it became predictable.</p><h4>OK, so how will I migrate to Moshi?</h4><p>It depends on the existing codebase. For me it was relatively easy, but time-consuming. And what I came to realize was that all the difficulty and overall challenge of migrating did not have anything to do with either Moshi or Gson whatsoever.</p><p>Read on to see how it worked out for me and how I actually cleaned and spruced up the data layer of my project along the way.</p><h3>Structure prior to migration</h3><h4>Messy data layer</h4><p>The following is a hypothetical, dead simple, scenario of a backend response and parsing, but one which is very indicative of how my data layer was.</p><p>Consider the following Json payload.</p><pre>{<br>    &quot;user_guid&quot;: &quot;abc123&quot;,<br>    &quot;user_first_name&quot;: &quot;Hulk&quot;,<br>    &quot;user_last_name&quot;: &quot;Hogan&quot;,<br>    &quot;user_age&quot;: 65<br>}</pre><p>Also consider the following model class, using Gson, written either by hand or by using an online conversion/generation tool.</p><pre>class UserModel {<br>    @SerializedName(&quot;user_guid&quot;)<br>    var guid: String? = null</pre><pre>    @SerializedName(&quot;user_first_name&quot;)<br>    var firstName: String? = null</pre><pre>    @SerializedName(&quot;user_last_name&quot;)<br>    var lastName: String? = null,</pre><pre>    @SerializedName(&quot;user_age&quot;)<br>    var age: Int? = null<br>}</pre><p>Even though this seems nice and neat, it’s not. It is not flexible and it adds unnecessary, insecure and untestable logic (since by going from user_guid to guid I’m performing an actual mapping) and overhead into code that does not need it and should not have it. Plus, data components should <a href="https://antonioleiva.com/clean-architecture-android/">not be visible to non needed layers</a> anyway, <a href="https://android.jlelse.eu/a-complete-idiots-guide-to-clean-architecture-2422f428946f">neither should they be used directly</a>.</p><p>So, first things first, what I decided to do, without even thinking about touching on Gson or Jackson or Moshi or whatever, was to…</p><h4>Dumb down the data</h4><p>Whether you like the Clean Architecture principals or not, it is a wonderful practice to have your response classes match your response payloads in the simplest way possible. No trickery with annotations, no subclassing, no logic, no nothing. Just get your data and parse them elsewhere.</p><p>So, I started by creating a data class that mirrored my payload absolutely, one which uses the primary constructor for all its properties.</p><pre>data class UserPayload(<br>    var user_guid: String,<br>    var user_first_name: String = &quot;Hulk&quot;,<br>    var user_last_name: String = &quot;Hogan&quot;,<br>    var user_age: Int? = null<br>)</pre><p>I left all naming or coding conventions aside. I had no use for them here. Also, I ignored all duplicate code, data classes provide enough <a href="https://proandroiddev.com/kotlin-data-classes-enough-boilerplate-c4647e475485">optimization</a> out of the box. And to make it interesting, I made the first and last as non nullable with default values and the age as nullable.</p><p>Next, was to strip the annotations from the Model class, turn it into a primary constructor data class and write a mapper to carry over the payload’s data to the Model. Here’s how the model became:</p><pre>data class UserModel(<br>    var guid: String,<br>    var firstName: String,<br>    var lastName: String,<br>    var age: Int? = null<br>)</pre><p>There’s numerous ways to do mapping. A simple, flexible and very <a href="https://mockk.io/#object-mocks">test-friendly</a> way, is to write a Kotlin object class.</p><pre>object UserMapper {<br>    fun map(payload: UserPayload) = UserModel(<br>        payload.user_guid<strong>,<br>        </strong>payload.user_first_name<strong>,<br>        </strong>payload.user_last_name<br>    ).<em>apply </em>{<br>        payload.user_age?.let { age = it }<strong><br>    </strong>}<strong><br></strong>}</pre><p>It took a very long and tedious while to do all this for the entirety of my project, but, in the end, I had a super clean data layer, that worked as before, still with Gson, nothing wrong or broken. Plus, all the models I was already using everywhere, became part of the domain layer. It all fit together seamlessly.</p><p>And, guess what, this reincarnated data layer doesn’t care in the <em>slightest</em> what library I use for serializing and deserializing. *Pats self on back*<br>Let’s move on.</p><h3>Migration process</h3><h4>Dependencies</h4><p>All the dependencies are available on the ReadMe of the project’s <a href="https://github.com/square/moshi">GitHub</a> repository…</p><pre>implementation &quot;com.squareup.moshi:moshi:$MOSHI&quot;<br>implementation &quot;com.squareup.moshi:moshi-kotlin:$MOSHI&quot;</pre><p>As of the time this article was being typed, the latest release of Moshi was 1.8.0. If you are using Retrofit, you also need the following.</p><pre>implementation &quot;com.squareup.retrofit2:converter-moshi:$RETROFIT&quot;</pre><h4>Dependency wrapper</h4><p>I have always believed that wrapping almost all 3rd party dependencies with an interim class is <a href="https://www.markphelps.me/2015/07/30/wrap-your-dependencies/">good</a> and <a href="https://hamishrickerby.com/2016/07/25/wrapping-3rd-party-code/">future-proof</a> practice, providing flexibility and protection against external breaking changes, regardless of platform or language. Since I was using serialization and deserialization not only for my HTTP client, I followed this practice once more.</p><pre>class JsonHandler(private val gson: Gson) {<br>    fun &lt;Type&gt; serialize(instance: Type): String {<br>        ...<br>    }<br>    <br>    fun &lt;Type&gt; deserialize(json: String, type: KClass&lt;Type&gt;): Type {<br>        ...<br>    } <br>}</pre><p>There’s no need to delve into this, changing the above wrapper was very simple and straighforward; simply switched from Gson to Moshi and adjusted the forwarding to the api appropriately.</p><p>On the other hand, if you have no use for a wrapper or you’re just not up for it, use dependency injection to your liking, and make sure to have…</p><h4>Single instantiation code</h4><p>Regardless of platform, project or language it is never advisable to have instances and initialization code scattered around. Making changes and tweaking things can be a nightmare in such cases. As for my project, I had a single project-wide Gson instance, injecting it with Dagger wherever needed.</p><p>It was not needed much anyway, just for the above wrapper and for Retrofit.</p><p>So I just changed the Dagger module providing it.</p><h4>Retrofit</h4><p>Like most, I use Retrofit as my HTTP client and migrating was no trouble. Simply switched from the Gson converter factory to the one provided by the dependency mentioned earlier.</p><pre>Retrofit.Builder()<br>    .addConverterFactory(MoshiConverterFactory.create(moshi))<br>    /* more initialization stuff */<br>    .build()</pre><h4>Type Adapters</h4><p>As with all the major Json apis, Moshi allows for creating adapters for serialization and deserialization of custom objects. To create one, all you need to do is write a new class with two functions; one taking a String as input and providing an object instance as output, and one doing the opposite.</p><p>You don’t need to subclass anything, just annotate the functions with @FromJson and @ToJson. <br>So, migrating from any type adapter to a Moshi type adapter is as simple as removing any subclassing and decorating (or re-decorating) your pre-existing functions.</p><p>If you are using code generation for type adapters, that’s not hard either. All you would need to do is <a href="https://medium.com/@joshuaavalon/migrate-from-gson-to-moshi-in-android-bfc9f357ff17">swap around some annotations</a> and that’s pretty much it.</p><p>Following is a simple adapter for handling dates with a custom format (unlike Gson, you can’t provide a custom date format to the instance builder, you need an adapter).</p><pre>class BackendDateAdapter {<br>    @ToJson<br>    fun toJson(value: Date): String = FORMATTER.format(value)<br><br>    @FromJson<br>    fun fromJson(value: String): Date = FORMATTER.parse(value)<br><br>    companion object {<br>        private val FORMATTER = <br>            SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;, Locale.<em>US</em>)<br>    }<br>}</pre><p>One last thing to keep in mind is that for Moshi to work with Kotlin correctly, you need to provide a new instance of the <strong>KotlinJsonAdapterFactory</strong> during the initialization process. So finally, here it comes…</p><h4>Initialization</h4><p>Nothing complex, with an easy as pie builder; <em>pleasantly</em> anticlimactic.</p><pre>fun moshi(): Moshi = Moshi.Builder()<br>    .add(KotlinJsonAdapterFactory())<br>    .add(BackendDateAdapter())<br>    /* more brilliant adapters */<br>    .build()</pre><h3>Conclusion</h3><p>I’m very happy with how Moshi performs and I’m delighted with how the project looks after the whole process.<br>Once again, it became very apparent to me that code structure and the quality of the fundamentals are key to any software engineering endeavor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e966ff163922" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How expressive can Kotlin code be? (aka fun with backticks, infixes and extensions)]]></title>
            <link>https://medium.com/@fanisveizis/how-expressive-can-kotlin-code-be-aka-fun-with-backticks-infixes-and-extensions-f730cdf45311?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f730cdf45311</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 17:13:19 GMT</pubDate>
            <atom:updated>2019-01-10T17:13:19.345Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOaukEcCLJj9oj37K7lyjg.jpeg" /></figure><blockquote>The answer to the above question is “<strong>ridiculously”</strong></blockquote><p>With some imagination and tinkering, Kotlin code can be like human speech, it can be like writing sentences and it can be so self-explanatory that it needs no comments at all.</p><p>Take the following code for example:</p><pre>compose a <em>`fun`</em>(&quot;privateHelloWorld&quot;) <strong>{<br>    </strong>&quot;&quot;&quot;<br>        print(&quot;Hello world, in private.&quot;)<br>    &quot;&quot;&quot;<br><strong>} </strong>`as` <em>private</em></pre><p>What does it do? It creates a function named privateHelloWorld which prints a simple String, and it’s private. But you already knew that.<br>Read on to see how it’s done.</p><h3>Introduction: Code generation with KotlinPoet</h3><p><a href="https://github.com/square/kotlinpoet">KotlinPoet</a> is the golden standard when it comes to generating Kotlin code. It’s an incredible project that builds upon the awesome features that <a href="https://github.com/square/javapoet/">JavaPoet</a> brought to the world of annotation processing and code generation.</p><p>The KotlinPoet API is inspired by JavaPoet and it follows the same builder logic, encouraging method chaining.</p><p>The equivalent code to the example above, using KotlinPoet alone, would be the following:</p><pre>FunSpec.builder(&quot;privateHelloWorld&quot;)<br>    .addModifiers(KModifier.PRIVATE)<br>    .addCode(<br>        &quot;&quot;&quot;<br>            print(&quot;Hello world, in private.&quot;)<br>        &quot;&quot;&quot;<br>    ).build()</pre><p>Not bad, right? But imagine this in the context of generating a whole package, complete with classes and top-level stuff. Not so good anymore, right?</p><p>But readability is not the only reason why I, personally, have been avoiding KotlinPoet and just using multi-line Kotlin strings for code generation.<br>The main reason is that I hate it when my Kotlin code <strong><em>doesn’t feel like</em></strong> Kotlin, and Java builder code with method chaining is as far away from Kotlin as I can think of.</p><p>I started working on the idea of wrapping the KotlinPoet functionality with a functional and expressive Kotlin DSL, utilizing some of the fancy stuff the language introduced.</p><p>First of all, I needed to model different code members to data classes and ended up with classes like PackageComposer, ClassComposer and FunctionComposer. To make their initialization awesome, I created top-level functions using…</p><h3>Backticks</h3><p>In Kotlin, reserved keywords can still be used as names for functions and properties if they are enclosed with backticks (`). So, I ended up with stuff like the following:</p><pre>inline fun `fun`(<br>    name: String, <br>    block: FunctionScope.() -&gt; String<br>) = FunctionComposer().<em>apply </em><strong>{ ... }</strong></pre><p>Using this function is pretty neat.</p><pre>`fun` (&quot;helloWorld&quot;) {<br>    &quot;&quot;&quot;<br>        print(&quot;Hello World!&quot;)<br>    &quot;&quot;&quot;<br>}</pre><p>To correctly use the above function in a larger scope, like within the declaration of a <strong>class</strong> or a <strong>package</strong>, I must pass its result as a parameter to a different function.</p><p>To do that and have it look pretty, I used…</p><h3>Infix Functions</h3><p>In Kotlin, a single parameter function marked with the infix notation, allows for invoking it without using the dot and for passing data to it without using parenthesis at all. <br>The drawback is that the receiver of the function must be <strong>clearly</strong> defined, which means it must precede the function at all times.</p><p>Having the whole expressiveness/readability in mind I decided to create top-level immutable properties named compose as the receivers and infix functions named a for handling the output of the aforementioned initialization functions, leading to code like compose a fun. Here’s their source:</p><pre>val ClassScope.compose = FunctionComposition()</pre><pre>infix fun FunctionComposition.a(`fun`: FunctionComposer) = `fun`</pre><p>ClassScope and other data classes named accordingly, are created for allowing certain functions to be available only within certain blocks of code, i.e. I can declare a function only inside the declaration of a class or a package.</p><p>FunctionComposition is how I decided to name the process of creating a function member. There’s other classes named similarly and their purpose is to model the functions and properties required to generate Kotlin code members.</p><h3>KotlinComposer</h3><p>Using the concepts described above, I started developing <a href="https://github.com/iFanie/KotlinComposer">KotlinComposer</a>, and with it, I generated the following Kotlin file…</p><pre>package com.izikode.izilib.kotlincomposer.app<br><br>class SimpleClass {<br>    fun helloWorld() {<br>        <em>print</em>(&quot;Hello world!&quot;)<br>    }<br><br>    private fun privateHelloWorld() {<br>        <em>print</em>(&quot;Hello world, in private.&quot;)<br>    }<br>}<br><br>fun topHelloWorld() {<br>    <em>print</em>(&quot;Hello world from top level!&quot;)<br>}</pre><p>… using the following code…</p><pre><em>compose </em>a <em>file</em>(&quot;SimpleClass&quot;) <strong>{<br>    </strong>compose a <em>`package`</em>(&quot;com.izikode.izilib.kotlincomposer.app&quot;) <strong>{</strong></pre><pre><strong>        </strong>compose a <em>`class`</em>(&quot;SimpleClass&quot;) <strong>{</strong></pre><pre><strong>            </strong>compose a <em>`fun`</em>(&quot;helloWorld&quot;) <strong>{<br>                </strong>&quot;&quot;&quot;<br>                    |print(&quot;Hello world!&quot;)<br>                &quot;&quot;&quot;.<em>trimMargin</em>()<br>            <strong>}<br><br>            </strong>compose a <em>`fun`</em>(&quot;privateHelloWorld&quot;) <strong>{<br>                </strong>&quot;&quot;&quot;<br>                    |print(&quot;Hello world, in private.&quot;)<br>                &quot;&quot;&quot;.<em>trimMargin</em>()<br>            <strong>} </strong>`as` <em>private<br><br>        </em><strong>}<br><br>        </strong>compose a <em>`fun`</em>(&quot;topHelloWorld&quot;) <strong>{<br>            </strong>&quot;&quot;&quot;<br>                |print(&quot;Hello world from top level!&quot;)<br>            &quot;&quot;&quot;.<em>trimMargin</em>()<br>        <strong>}<br><br>    }<br>}</strong></pre><p>Now compare this to plain KotlinPoet code for the exact same result…</p><pre>FileSpec.builder(&quot;com.izikode.izilib.kotlincomposer.app&quot;, &quot;SimpleClass&quot;)<br>    .addType(<br>        TypeSpec.classBuilder(&quot;SimpleClass&quot;)<br>            .addFunction(<br>                FunSpec.builder(&quot;helloWorld&quot;)<br>                    .addCode(<br>                        &quot;&quot;&quot;<br>                            |print(&quot;Hello world!&quot;)<br>                        &quot;&quot;&quot;.<em>trimMargin</em>()<br>                    ).build()<br>            ).addFunction(<br>                FunSpec.builder(&quot;privateHelloWorld&quot;)<br>                    .addModifiers(KModifier.PRIVATE)<br>                    .addCode(<br>                        &quot;&quot;&quot;<br>                            |print(&quot;Hello world, in private.&quot;)<br>                        &quot;&quot;&quot;.<em>trimMargin</em>()<br>                    ).build()<br>            ).build()<br>    ).addFunction(<br>        FunSpec.builder(&quot;topHelloWorld&quot;)<br>            .addCode(<br>                &quot;&quot;&quot;<br>                    |print(&quot;Hello world from top level!&quot;)<br>                &quot;&quot;&quot;.<em>trimMargin</em>()<br>            ).build()<br>    ).build()</pre><p>The difference is huge.</p><p>If you find any of this interesting, head on to GitHub and share your thoughts. The project is in it’s very <strong>very VERY</strong> early stages so any feedback would be much appreciated.</p><p><a href="https://github.com/iFanie/KotlinComposer">iFanie/KotlinComposer</a></p><h3>Conclusion</h3><p>Kotlin allows for thinking (and coding) outside the box and with it we can create some truly awesome stuff…</p><p>… come to think about it, we already have so much awesomeness in such a short time. Let’s see what more we can do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f730cdf45311" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using custom CSS styles and JS scripts on Android WebViews]]></title>
            <link>https://medium.com/@fanisveizis/using-custom-css-styles-and-js-scripts-on-android-webviews-6da0502d6595?source=rss-38367c2ec35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6da0502d6595</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Fanis Veizis]]></dc:creator>
            <pubDate>Sun, 23 Dec 2018 16:25:06 GMT</pubDate>
            <atom:updated>2018-12-23T16:25:06.051Z</atom:updated>
            <content:encoded><![CDATA[<p>Using custom <strong>CSS </strong>styles and <strong>JS </strong>scripts on <strong>Android WebViews</strong></p><p>Android WebViews permit loading custom CSS and JavaScript code in the contents of a loaded webpage. <br>All you need to do is override the onPageFinished function of the WebViewClient you provide to your WebView, and call loadUrl with your custom code.</p><p>The best way to approach this is to create the appropriate JavaScript nodes for your code; a style node for CSS and a script node for JavaScript. Let’s write those scripts now, shall we?</p><p>The following JavaScript code creates a new node on the DOM containing the CSS style we provide it with.</p><pre>var node = document.createElement(&#39;style&#39;);<br><br>node.type = &#39;text/css&#39;;<br>node.innerHTML = &#39;MY_CSS_STYLE&#39;;<br><br>document.head.appendChild(node);</pre><p>The following JavaScript code creates a new node on the DOM containing the JS script we provide it with.</p><pre>var node = document.createElement(&#39;script&#39;);<br><br>node.type = &#39;text/javascript&#39;;<br>node.innerHTML = &#39;MY_JS_SCRIPT&#39;;<br><br>document.body.appendChild(node);</pre><p>To get the above code to work and correctly create the nodes after the contents of the webpage have been loaded, we need to wrap it with a self-invoking JavaScript function. This isn’t complicated either.</p><pre>javascript:(function() { MY_JS_CODE })()</pre><p>So how can one combine all the above and inject code into an Android WebView? <br>Going back to the onPageFinished function of the WebViewClient implementation, let’s inject a very simple style that will give Google a dark theme; code is in <strong>Kotlin,</strong> using the multi-line string operator.</p><pre>override fun onPageFinished(view: WebView, url: String) {<br>    val code = &quot;&quot;&quot;javascript:(function() { <br>    <br>        var node = document.createElement(&#39;style&#39;);<br><br>        node.type = &#39;text/css&#39;;<br>        node.innerHTML = &#39;body {<br>            color: white;<br>            background-color: black;<br>        }&#39;;<br><br>        document.head.appendChild(node);<br>     <br>    })()&quot;&quot;&quot;.<em>trimIndent</em>()<br><br>    loadUrl(code)<strong><br></strong>}</pre><p>Done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtqL5b_n4PlUH0SlciYCGA.png" /></figure><p>You can find the above functionality in a tidy, neat little library I developed called <a href="https://github.com/iFanie/VeinView">VeinView</a>. It wraps all the above in a custom WebView and a custom Client, and allows for loading String code or RAW Android resources.</p><p>Happy holidays!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6da0502d6595" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>