<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>What I should have said</title>
 <link href="http://0.0.0.0:4000/atom.xml" rel="self"/>
 <link href="http://0.0.0.0:4000/"/>
 <updated>2022-08-18T15:46:07-05:00</updated>
 <id>http://0.0.0.0:4000</id>
 <author>
   <name>Duncan McGregor</name>
   <email>duncan@oneeyedmen.com</email>
 </author>

 
 <entry>
   <title>Defining an Operator Invoke Extension Function on Kotlin Function Types</title>
   <link href="http://0.0.0.0:4000/function-extension-functions-on-functions.html"/>
   <updated>2022-08-18T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/function-extension-functions-on-functions</id>
   <content type="html">&lt;p&gt;I’ve been producing a lot of &lt;a href=&quot;https://www.youtube.com/channel/UCWZnyGwHUjIcP2mdz2B5qzQ/&quot;&gt;YouTube Videos&lt;/a&gt; lately. They’re
about refactoring and TDD and all that good stuff - you really should subscribe.&lt;/p&gt;

&lt;p&gt;In one episode I have a class that takes a function type property in its constructor. The property defines a strategy for how to update items.&lt;/p&gt;

&lt;p&gt;Here I’m going to go off on the tangent that Jekyll’s home-page generation fails if you have a code block that is 
split on the front page. So this text is just to move this code block down the page:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Stock(
    private val stockFile: File,
    private val zoneId: ZoneId,
    private val updater: (items: List&amp;lt;Item&amp;gt;, days: Int, on: LocalDate) -&amp;gt; List&amp;lt;Item&amp;gt;
) {
    fun stockList(now: Instant): Result4k&amp;lt;StockList, StockListLoadingError&amp;gt; =
        stockFile.loadItems().flatMap { stockList: StockList -&amp;gt;
            val daysOutOfDate = stockList.lastModified.daysTo(now, zoneId).toInt()
            when {
                daysOutOfDate &amp;gt; 0 -&amp;gt; update(stockList, updater, now, daysOutOfDate, zoneId).savedTo(stockFile, now)
                else -&amp;gt; Success(stockList)
            }
        }
}

private fun update(
    stockList: StockList,
    updater: (items: List&amp;lt;Item&amp;gt;, days: Int, on: LocalDate) -&amp;gt; List&amp;lt;Item&amp;gt;,
    now: Instant,
    daysOutOfDate: Int,
    zoneId1: ZoneId
): StockList = stockList.copy(
    lastModified = now,
    items = updater(stockList.items, daysOutOfDate, LocalDate.ofInstant(now, zoneId1))
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So a &lt;code&gt;Stock&lt;/code&gt; is an object that can load a &lt;code&gt;StockList&lt;/code&gt; from a file, updating the stock &lt;code&gt;Item&lt;/code&gt;s using a strategy
defined by the &lt;code&gt;updater&lt;/code&gt; function. It’s all a bit of a tangle, yes, but this is the middle of a refactor.&lt;/p&gt;

&lt;p&gt;The nastiness of that &lt;code&gt;update&lt;/code&gt; function is because &lt;code&gt;updater&lt;/code&gt; has the wrong signature as far this code is concerned.
We need it to work on a &lt;code&gt;StockList&lt;/code&gt;, but it is defined on &lt;code&gt;List&amp;lt;Item&amp;gt;&lt;/code&gt; because that’s a simpler interface for our 
clients.&lt;/p&gt;

&lt;p&gt;So here’s a ‘cute’ trick. Take the &lt;code&gt;updater&lt;/code&gt; parameter to &lt;code&gt;update&lt;/code&gt; and make it the receiver.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;...
                daysOutOfDate &amp;gt; 0 -&amp;gt; updater.update(stockList, now, daysOutOfDate, zoneId).savedTo
...
private fun ((items: List&amp;lt;Item&amp;gt;, days: Int, on: LocalDate) -&amp;gt; List&amp;lt;Item&amp;gt;).update(
    stockList: StockList,
    now: Instant,
    daysOutOfDate: Int,
    zoneId1: ZoneId
): StockList = stockList.copy(
    lastModified = now,
    items = this(stockList.items, daysOutOfDate, LocalDate.ofInstant(now, zoneId1))
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now convert it to an &lt;code&gt;operator fun&lt;/code&gt; &lt;code&gt;invoke&lt;/code&gt; extension&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;...
                daysOutOfDate &amp;gt; 0 -&amp;gt; updater.invoke(stockList, now, daysOutOfDate, zoneId).savedTo(stockFile, now)
...

private operator fun ((items: List&amp;lt;Item&amp;gt;, days: Int, on: LocalDate) -&amp;gt; List&amp;lt;Item&amp;gt;).invoke(
    stockList: StockList,
    now: Instant,
    daysOutOfDate: Int,
    zoneId1: ZoneId
): StockList = stockList.copy(
    lastModified = now,
    items = this(stockList.items, daysOutOfDate, LocalDate.ofInstant(now, zoneId1))
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and finally remove the vestigial &lt;code&gt;invoke&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Stock(
    private val stockFile: File,
    private val zoneId: ZoneId,
    private val updater: (items: List&amp;lt;Item&amp;gt;, days: Int, on: LocalDate) -&amp;gt; List&amp;lt;Item&amp;gt;
) {
    fun stockList(now: Instant): Result4k&amp;lt;StockList, StockListLoadingError&amp;gt; =
        stockFile.loadItems().flatMap { stockList: StockList -&amp;gt;
            val daysOutOfDate = stockList.lastModified.daysTo(now, zoneId).toInt()
            when {
                daysOutOfDate &amp;gt; 0 -&amp;gt; updater(stockList, now, daysOutOfDate, zoneId).savedTo(stockFile, now)
                else -&amp;gt; Success(stockList)
            }
        }
}

private operator fun ((items: List&amp;lt;Item&amp;gt;, days: Int, on: LocalDate) -&amp;gt; List&amp;lt;Item&amp;gt;).invoke(
    stockList: StockList,
    now: Instant,
    daysOutOfDate: Int,
    zoneId1: ZoneId
): StockList = stockList.copy(
    lastModified = now,
    items = this(stockList.items, daysOutOfDate, LocalDate.ofInstant(now, zoneId1))
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So what we have is an operator invoke function defined as an extension on a function type.
This way we have ‘seamlessly’ (well, there is a seam, but it is invisible) converted our &lt;code&gt;updater&lt;/code&gt; from the function we
have to the function we want.&lt;/p&gt;

&lt;p&gt;To be honest, I’m pretty sure that the benefit is not worth the cleverness here, but I present the technique on the 
off-chance that it digs you out of a hole somewhere. If it does, please let me know on &lt;a href=&quot;https://twitter.com/duncanmcg&quot;&gt;Twitter&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Writing Software to Write About Writing Software - Part 1</title>
   <link href="http://0.0.0.0:4000/book-software-part-1.html"/>
   <updated>2021-10-05T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/book-software-part-1</id>
   <content type="html">&lt;p&gt;O’Reilly recently published the Kotlin book I wrote with Nat Pryce: &lt;a href=&quot;https://java-to-kotlin.dev/&quot;&gt;Java to Kotlin: A Refactoring Guidebook&lt;/a&gt;. I thought it might be interesting to write about the software we wrote to support our writing.&lt;/p&gt;

&lt;p&gt;O’Reilly’s publishing system (Atlas) will accept Word, DocBook or &lt;a href=&quot;https://asciidoctor.org/&quot;&gt;AsciiDoc&lt;/a&gt; manuscripts. My experience trying to manage simultaneous work in large Word documents has not been great, although perhaps Office 365 is better - I’ve been generally impressed when I have used it. Being developers though, we naturally gravitated to plain-text formats, and our editors steered us towards AsciiDoc rather than the XML-based DocBook. AsciiDoc is a lot like Markdown in that the formatting works reasonably in plain text and can then be rendered into more sophisticated formats like HTML and PDF. Unlike Markdown, it only really has one dialect, but the tooling has migrated from &lt;a href=&quot;https://asciidoc-py.github.io/&quot;&gt;Python&lt;/a&gt; to &lt;a href=&quot;https://github.com/asciidoctor&quot;&gt;Ruby&lt;/a&gt; which has led to some versioning issues. We also discovered quite late in the day that Atlas is based on an old and relatively buggy version of AsciiDoctor (the toolchain), but by that time we were committed.&lt;/p&gt;

&lt;p&gt;The Atlas publishing system hosts a Git repository, so you can push book source in the supported formats and then click a button in the UI to render a PDF, HTML or EPUB book, which is available to download after a minute or so. For reasons that we couldn’t fathom, it doesn’t just automatically build every commit. At first Nat built an AsciiDoctor Docker image so that we could render locally, but once we discovered that Atlas was both customised and out of date we settled on using it rather than a local build to be sure that we remained compatible with its idiosyncrasies.&lt;/p&gt;

&lt;p&gt;Our book has many, many, many code examples. Obviously we want to make sure that these compile and work as expected, so just typing them into the manuscript wasn’t an option. In my &lt;a href=&quot;https://leanpub.com/episodes&quot;&gt;previous attempt&lt;/a&gt; at writing a book I had chosen to embed the book text into comments in Kotlin source, so I could manage both text and source in IntelliJ. So I had Kotlin source like:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;import org.junit.*

/*-
## Title

This is book text - anything in /*- … -*/ blocks is extracted to Markdown.

Code in //` blocks is also extracted.
-*/
class Test {

//`
    @Test fun `2 plus 2 is 4`() {
        assertEquals(4, add(2, 2))
    }
//`
}
/*-
More text here.
 */
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This would render (to Markdown) as:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;## Title

This is book text - anything in /*- … -*/ blocks is extracted to Markdown.

Code in //` blocks is also extracted.

```kotlin
@Test fun `2 plus 2 is 4`() {
    assertEquals(4, add(2, 2))
}
.```

More text here.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And no, there shouldn’t be a dot before the &lt;code&gt;kotlin&lt;/code&gt; code block closure, but this blog is itself written in Markdown, which appears, at least in its Jekyll incarnation, to be unable to render itself. Apart from that sort of issue, this scheme worked OK, but it was a challenge to manage multiple versions of the same code. I bodged it by using hidden &lt;code&gt;object&lt;/code&gt; namespaces and occasionally changing packages, but it was clear that the approach wasn’t ideal for a book which would be showing the evolution of code through multiple refactorings.&lt;/p&gt;

&lt;p&gt;For our book then, Nat and I decided to separate the manuscript text and example code, pulling the text from the code into the AsciiDoc source with markers. So in our AsciiDoc source we might write:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;A little compiler magic allows Kotlin code to accept a `java.util.List` as a `kotlin.collections.List`:

// begin-insert: src/test/java/collections/ListInteropTest.kt
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the best traditions of developer documentation we then wrote code to fetch the contents of &lt;code&gt;ListInteropTest.kt&lt;/code&gt; and expand it into the AsciiDoc.&lt;/p&gt;

&lt;p&gt;Ordinarily we would take the AsciiDoc source with these markers and write a new file with the inserted code. This new file would then be sent to AsciiDoctor to render. In practice this doesn’t work well, because we’d like the book source that we’re editing to be as close to the rendered output as reasonable (this is the point of ASCII-based markup after all), and in particular to be able to see the code that we’re writing about there in the editor where we are writing about it.&lt;/p&gt;

&lt;p&gt;So we made the expansion software overwrite the AsciiDoc source document with its expanded version. By making the markers AsciiDoc comments we can leave them in the file when we expand them. They aren’t rendered in the final output, but remain in the book source so that we can navigate to the included file, and replace them with the new version when the code is changed.&lt;/p&gt;

&lt;p&gt;The result is that after running the expansion code our AsciiDoc would be:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;A little compiler magic allows Kotlin code to accept a `java.util.List` as a `kotlin.collections.List`:

// begin-insert: src/test/java/collections/ListInteropTest.kt
[source,kotlin]
----
val aList: List&amp;lt;String&amp;gt; = SomeJavaCode.mutableListOfStrings(&quot;0&quot;, &quot;1&quot;)
aList.removeAt(1) // doesn't compile
----
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a trick that has worked well for me in the past. Nat was resistant to the idea at first, and neither of us really liked having a tool that &lt;em&gt;overwrites&lt;/em&gt; source files, but in this case it is expedient because it means that the code examples are expanded in the Git version, and we didn’t have to work out how to run some sort of pre-build step on Atlas. A handy side-effect is that if we modified the rendering code we could run it and see any behaviour changes as Git diffs to the AsciiDoc source rather than having to compare rendered output - the book source acts as a kind of approval test of its expansion code.&lt;/p&gt;

&lt;p&gt;The observant reader might be wondering how &lt;code&gt;ListInteropTest.kt&lt;/code&gt; compiles if &lt;code&gt;aList.removeAt(1)&lt;/code&gt; doesn’t. Well I’ve been hiding a detail - the book source actually has:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;// begin-insert: src/test/java/collections/ListInteropTest.kt#immutable
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;code&gt;immutable&lt;/code&gt; is a marker that controls what from the code source is expanded into the book source. With no marker the whole file is inserted (minus import statements and leading and trailing whitespace). With a marker, well, here is the relevant section of the source file:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun testKotlinCanAcceptJavaListAsImmutableList() {
        /// begin: immutable
        val aList: List&amp;lt;String&amp;gt; = SomeJavaCode.mutableListOfStrings(&quot;0&quot;, &quot;1&quot;)
        /// end: immutable
        /*
        /// begin: immutable
        aList.removeAt(1) // doesn't compile
        /// end: immutable
        */

        assertEquals(listOf(&quot;0&quot;, &quot;1&quot;), aList)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see that the code is a test that checks that the behaviour we are documenting is as we say it is. We have only rendered lines between &lt;code&gt;/// begin&lt;/code&gt; and &lt;code&gt;/// end&lt;/code&gt; markers with the same tag as the fragment. This gives the desired behaviour in this case, which is that the compiler doesn’t see the commented out code when we run our tests on the Kotlin source, and the book reader doesn’t see the comments that hide it from the compiler:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;A little compiler magic allows Kotlin code to accept a `java.util.List` as a `kotlin.collections.List`:

// begin-insert: src/test/java/collections/ListInteropTest.kt
[source,kotlin]
----
val aList: List&amp;lt;String&amp;gt; = SomeJavaCode.mutableListOfStrings(&quot;0&quot;, &quot;1&quot;)
aList.removeAt(1) // doesn't compile
----
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We ended up with a set of &lt;code&gt;///&lt;/code&gt;-prefixed source markers to control what was rendered. &lt;code&gt;/// begin&lt;/code&gt; and &lt;code&gt;/// end&lt;/code&gt; we’ve seen, &lt;code&gt;/// mute&lt;/code&gt; and &lt;code&gt;/// resume&lt;/code&gt; acted in the opposite way and also allowed us to specify some text to show in place of the elided code. So our source Java might be:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;/// begin: excerpt
public class Person {
    private final String firstName;
    private final String lastName;

    public Person(
        String firstName,
        String lastName
    ) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    /// mute: excerpt [... getters, equals, hashCode]
    public String getFirstName() { return firstName; }

    public String getLastName() { return lastName; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return firstName.equals(person.firstName) &amp;amp;&amp;amp; lastName.equals(person.lastName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(firstName, lastName, townOrCity, postalCode, countryCode);
    }
    /// resume: excerpt
}
/// end: excerpt
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but the AsciiDoc would expand thus:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;// begin-insert: src/main/java/builders/Person.java#excerpt
[source,java]
----
public class Person {
    private final String firstName;
    private final String lastName;

    public Person(
        String firstName,
        String lastName,
    ) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    ... getters, equals, hashCode
}
----
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We flirted with other directives, but with a little creativity these were sufficient to cover all our needs for showing and hiding code. The snipping of code given a source file and marker name, and the expansion of the snipped code into the book source were performed by Kotlin invoked by a Gradle build. Inevitably this involved increasingly complex regular expressions and little territorial wars between Nat and me, but overall it worked well for us. You can see &lt;a href=&quot;https://github.com/java-to-kotlin/book&quot;&gt;our code on GitHub&lt;/a&gt;, but the whole build system is probably an area where you’re best writing your own version so that you can customise it to make sense to you.&lt;/p&gt;

&lt;p&gt;The tooling as described so far worked well for relatively static code examples, but our book is about refactoring, and in particular long-running sequences of refactorings to migrate from Java to idiomatic Kotlin. We needed to find a way to render multiple versions of the same code, and preferably to show the differences between code at different versions.&lt;/p&gt;

&lt;p&gt;We toyed with keeping different versions of the code in different source roots, or different packages, but this turns out to be unsupportable for all the reasons you can probably predict. Instead, we decided to keep the history in Git, and extend the expansion code to fetch a particular version.&lt;/p&gt;

&lt;p&gt;The simplest thing that could possibly work is just to include the Git SHA as well as the file path and marker in the AsciiDoc comments:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;// begin-insert: 67b499c6:src/main/java/travelator/itinerary/Route.java#route
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now fetch &lt;code&gt;src/main/java/travelator/itinerary/Route.java&lt;/code&gt; from the commit with SHA &lt;code&gt;67b499c6&lt;/code&gt;, apply the snippeting with the &lt;code&gt;route&lt;/code&gt; marker, and expand the results inline in the AsciiDoc.&lt;/p&gt;

&lt;p&gt;This turns out, though, to be too simple to &lt;em&gt;actually&lt;/em&gt; work. The problem is that writing is an iterative process, and that applies both to the book text and the example code. If we were just documenting the history of a codebase it would be fine, but in practice we found ourselves having to go back to commits and edit them. Sometimes this would be to add snippeting markers or reformatting to fit the book pages, but often we would rework a refactoring from scratch. In any case, editing a commit changes its SHA, and if you rebase later commits, all their SHAs too, so that we would be constantly having to update many markers.&lt;/p&gt;

&lt;p&gt;We needed something more stable than SHAs, and settled on commit comments. We prefixed the comments for code versions that we wanted to reference with, for example &lt;code&gt;encapsulated-collections.0&lt;/code&gt; and then said:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;// begin-insert: encapsulated-collections.0:src/main/java/travelator/itinerary/Route.java#route
// end-insert
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the expansion code just has to find a commit with a comment prefixed with &lt;code&gt;encapsulated-collections.0&lt;/code&gt;. I say &lt;em&gt;just&lt;/em&gt;, but in practice searching a repo for a commit is quite expensive, so in the end Nat wrote a script to apply tags with all the versions to these commits:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;#!/bin/bash
set -eou pipefail

basedir=&quot;$(realpath $(dirname &quot;$0&quot;))&quot;
current=&quot;$basedir/build/current-tagged&quot;
last=&quot;$basedir/build/last-tagged&quot;

cd ../refactoring-to-kotlin-code

function active_branches() {
  git show-ref --heads | grep -v 'refs/heads/attic/' | grep -v 'refs/heads/dummy-master'
}

active_branches | cut -d ' ' -f 1 | shasum &amp;gt; &quot;$current&quot;

if ! diff -q -N &quot;$current&quot; &quot;$last&quot; &amp;gt; /dev/null
then
    tagfmt='*.[0-9]*'

    # delete tags
    git tag -l &quot;$tagfmt&quot; | xargs git tag -d &amp;gt; /dev/null
    
    # Recreate tags
    git log --topo-order --format=&quot;%H %S %s&quot; $(active_branches | cut -d ' ' -f 2) | awk '
        $3 ~ /([a-z0-9_\-]+)([.][0-9]+)+/ &amp;amp;&amp;amp; $3 != tagname {
            commit = $1
            branch = $2
            tagname = $3

            if (tagname in commits &amp;amp;&amp;amp; commits[tagname] != commit) {
                print &quot;ERROR: &quot; tagname &quot; refers to different commits in branches &quot; branch &quot; and &quot; branches[tagname] &amp;gt; &quot;/dev/stderr&quot;
                exit 1
            }

            branches[tagname] = branch
            commits[tagname] = commit

            print tagname, commit
        }
    ' | xargs -n 2 git tag -f
    mv &quot;$current&quot; &quot;$last&quot;
fi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;No, I’ve no idea how it works either, but it does, and when it doesn’t, it’s Nat’s problem. My problem was fetching the version of a file with a particular tag (&lt;code&gt;encapsulated-collections.0&lt;/code&gt; in this case), which is just &lt;code&gt;git show encapsulated-collections.0:src/main/java/travelator/itinerary/Route.java&lt;/code&gt; in the right directory. The expanding code runs this when it sees the tag prefix and then proceeds as before. If you’re interested the latest version of the expanding code is &lt;a href=&quot;https://github.com/java-to-kotlin/book/tree/just-tools/buildSrc/src/main/java/book&quot;&gt;available on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;At this point we have a toolchain that allows us to fetch code at a particular version from a Git history and expand it, with some modifications, into the book source. We settled on a strategy of having each chapter in its own &lt;code&gt;.asciidoc&lt;/code&gt; file: &lt;code&gt;06-java-to-kotlin-collections.asciidoc&lt;/code&gt;, &lt;code&gt;07-actions-to-calculations.asciidoc&lt;/code&gt; etc. This meant that we could each work on different chapters without merge issues. Naming the chapters with their number meant that we were constantly renaming them as we reorganised the book, but Git seems to cope well with renaming these days. All the chapters were pulled into a single text with a global AsciiDoc file that used &lt;code&gt;include&lt;/code&gt; directives:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ascidoc&quot;&gt;:xrefstyle: full
:sectnums:
:sectnumlevels: 2

[role=&quot;pagenumrestart&quot;]

include::chapters/01-intro.asciidoc[]

// Foundation
include::chapters/02-java-to-kotlin-projects.asciidoc[]
include::chapters/03-java-to-kotlin-classes.asciidoc[]
include::chapters/04-optional-to-nullable.asciidoc[]
include::chapters/05-beans-to-values.asciidoc[]
include::chapters/06-java-to-kotlin-collections.asciidoc[]
include::chapters/07-actions-to-calculations.asciidoc[]

// Function structure
include::chapters/08-static-methods-to-top-level-functions.asciidoc[]
include::chapters/09-multi-to-single-expression-functions.asciidoc[]
include::chapters/10-functions-to-extension-functions.asciidoc[]
include::chapters/11-methods-to-properties.asciidoc[]
include::chapters/12-functions-to-operators.asciidoc[]

// Pipelines
include::chapters/13-streams-to-sequences.asciidoc[]
include::chapters/14-accumulating-objects-to-transformations.asciidoc[]

// Types
include::chapters/15-encapsulated-collections-to-typealiases.asciidoc[]
include::chapters/16-interfaces-to-functions.asciidoc[]
include::chapters/17-mocks-to-maps.asciidoc[]
include::chapters/18-open-to-sealed-classes.asciidoc[]

// Layers
include::chapters/19-throwing-to-returning.asciidoc[]
include::chapters/20-performing-io-to-passing-data.asciidoc[]
include::chapters/21-exceptions-to-values.asciidoc[]
include::chapters/22-classes-to-functions.asciidoc[]

// Conclusion
include::chapters/23-continuing-the-journey.asciidoc[]

include::bibliography.asciidoc[]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Actually, Atlas uses another file, &lt;code&gt;atlas.json&lt;/code&gt; to specify what it will render and how. In our case this includes other files that make up the whole book but which O’Reilly manage:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;files&quot;: [
    &quot;cover.html&quot;,
    &quot;praise.html&quot;,
    &quot;titlepage.html&quot;,
    &quot;copyright.html&quot;,
    &quot;toc.html&quot;,
    &quot;text/src/preface.asciidoc&quot;,
    &quot;text/src/content.asciidoc&quot;,
    &quot;ix.html&quot;,
    &quot;author_bio.html&quot;,
    &quot;colo.html&quot;
  ]
  //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We kept versioned example code in a separate repo to the book text and toolchain - that way we could manage the evolution of the text and examples separately. In the code repo we kept each running example in a separate branch, so that we could modify one example without having to update all the others. For example, there is one example that starts in &lt;em&gt;Chapter 10: Functions to Extension Functions&lt;/em&gt;, is further refactored in &lt;em&gt;Chapter 20: Performing I/O to Passing Data&lt;/em&gt;, and again in &lt;em&gt;Chapter 21: Exceptions to Values&lt;/em&gt;. This code is on a branch named &lt;code&gt;customer-report&lt;/code&gt;, and has commits with labels like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    exceptions-to-values.7 : flatMap errors
    exceptions-to-values.6 : Collect reasons for failure
    ...
    io-to-data.2 : Show calculation in check
    io-to-data.1 : convert tests to Kotlin
    ...
    extensions.4 : Fix compile
    extensions.3 : Convert HighValueCustomersReport to Kotlin (doesn't compile)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running Nat’s script from earlier will give these commits tags:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-markdown&quot;&gt;    exceptions-to-values.7
    exceptions-to-values.6
    ...
    io-to-data.2
    io-to-data.1
    ...
    extensions.4
    extensions.3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Looking in, for example, &lt;code&gt;20-performing-io-to-passing-data.asciidoc&lt;/code&gt; we find:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-asciidoc&quot;&gt;// begin-insert: io-to-data.2:src/test/java/travelator/marketing/HighValueCustomersReportTests.kt#check
[source,kotlin]
----
private fun check(
    inputLines: List&amp;lt;String&amp;gt;,
    expectedLines: List&amp;lt;String&amp;gt;
) {
    val output = StringWriter()
    val reader = StringReader(inputLines.joinToString(&quot;\n&quot;))
    generate(reader, output)
    val outputLines = output.toString().lines()

    assertEquals(expectedLines, outputLines)
}
----
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can imagine, we got pretty good at interactively rebasing the code on these branches, but still it was easy to break code, so that something that had worked no longer did. In the next installment I’ll look at how we made sure that all the code that we published in the book worked as expected.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Extracting an Extension Function from a Call Chain</title>
   <link href="http://0.0.0.0:4000/extract-extension-from-chain.html"/>
   <updated>2020-12-01T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/extract-extension-from-chain</id>
   <content type="html">&lt;p&gt;Kotlin extension functions let us express our algorithms as functional pipelines.
We can see these as chains of calls, where the output of a stage is fed into the next. 
Here’s a chain that reads lines representing &lt;code&gt;CustomerData&lt;/code&gt; from a &lt;code&gt;reader&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = reader
    .buffered()
    .lineSequence()
    .drop(1) // header
    .map(String::toCustomerData)
    .filter { it.score &amp;gt;= 10 }
    .sortedBy(CustomerData::score)
    .toList()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Chains like this are nice and easy to read (at least for English speakers), as we start at the top left and work our way to the bottom right.
This one is long enough to be intimidating though, and mixes concerns at different levels. 
It would be nice to break it into named sections.&lt;/p&gt;

&lt;p&gt;We can do that by extracting extension methods that represent parts of the call chain.
In this case we’d like to extract the &lt;code&gt;drop(1)&lt;/code&gt; to &lt;code&gt;.filter&lt;/code&gt; lines into a function named &lt;code&gt;valuableCustomers&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;IntelliJ doesn’t (yet) have a single refactoring that will do that.
We can combine individual refactorings to get there safely though.&lt;/p&gt;

&lt;p&gt;First we select from the start of the expression to end of the chain that we want.
In this case, from &lt;code&gt;reader&lt;/code&gt; to the end of the filter line.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;                        reader
    .buffered()
    .lineSequence()
    .drop(1) // header
    .map(String::toCustomerData)
    .filter { it.score &amp;gt;= 10 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;“Extract Function”, calling it &lt;code&gt;valuableCustomers&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = valuableCustomers(reader)
    .sortedBy(CustomerData::score)
    .toList()

private fun valuableCustomers(reader: Reader) = reader
    .buffered()
    .lineSequence()
    .drop(1) // header
    .map(String::toCustomerData)
    .filter { it.score &amp;gt;= 10 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we select from the start of the extracted function to the beginning of chain that we want.
In this case, from &lt;code&gt;reader&lt;/code&gt; to the end of &lt;code&gt;lineSequence()&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;                                                reader
    .buffered()
    .lineSequence()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;“Introduce Parameter”.
As there will be no uses of the old parameter once the new one is there, it shows that &lt;code&gt;reader&lt;/code&gt; will be deleted. 
Accept the refactor.&lt;/p&gt;

&lt;p&gt;That might work, but there is a currently &lt;a href=&quot;https://youtrack.jetbrains.com/issue/IDEA-256518&quot;&gt;a bug in IntelliJ&lt;/a&gt; that means that in some cases it doesn’t.
It doesn’t work here, leaving us with both parameters and losing the &lt;code&gt;buffered().lineSequence()&lt;/code&gt; code altogether:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = valuableCustomers(reader)
    .sortedBy(CustomerData::score)
    .toList()

private fun valuableCustomers(reader: Reader, sequence: Sequence&amp;lt;String&amp;gt;) = sequence
    .drop(1) // header
    .map(String::toCustomerData)
    .filter { it.score &amp;gt;= 10 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If this happens, we “Undo” (keeping the &lt;code&gt;reader&lt;/code&gt; to &lt;code&gt;lineSequence()&lt;/code&gt; selection) and “Introduce Local Variable”:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private fun valuableCustomers(reader: Reader): Sequence&amp;lt;CustomerData&amp;gt; {
    val lineSequence = reader
        .buffered()
        .lineSequence()
    return lineSequence
        .drop(1) // header
        .map(String::toCustomerData)
        .filter { it.score &amp;gt;= 10 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we select the whole new statement, from &lt;code&gt;val&lt;/code&gt; to &lt;code&gt;lineSequence()&lt;/code&gt; and “Introduce Parameter”.
This is the point that directly introducing the parameter should have got to:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = valuableCustomers(
    reader
        .buffered()
        .lineSequence()
)
    .sortedBy(CustomerData::score)
    .toList()

private fun valuableCustomers(lineSequence: Sequence&amp;lt;String&amp;gt;): Sequence&amp;lt;CustomerData&amp;gt; {
    return lineSequence
        .drop(1) // header
        .map(String::toCustomerData)
        .filter { it.score &amp;gt;= 10 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now Alt-Enter on the &lt;code&gt;lineSequence&lt;/code&gt; parameter and “Convert parameter to receiver”:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = reader
    .buffered()
    .lineSequence().valuableCustomers()
    .sortedBy(CustomerData::score)
    .toList()

private fun Sequence&amp;lt;String&amp;gt;.valuableCustomers(): Sequence&amp;lt;CustomerData&amp;gt; {
    return drop(1) // header
        .map(String::toCustomerData)
        .filter { it.score &amp;gt;= 10 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Alt-Enter on &lt;code&gt;return&lt;/code&gt; and “Convert to expression body”, and then tidying up the formatting gives us:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = reader
    .buffered()
    .lineSequence()
    .valuableCustomers()
    .sortedBy(CustomerData::score)
    .toList()

private fun Sequence&amp;lt;String&amp;gt;.valuableCustomers(): Sequence&amp;lt;CustomerData&amp;gt; = 
    drop(1) // header
    .map(String::toCustomerData)
    .filter { it.score &amp;gt;= 10 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we’re done, at least until JetBrains give us an “Extract extension function” refactor to do it automagically.&lt;/p&gt;

&lt;p&gt;Well, almost done.&lt;/p&gt;

&lt;p&gt;Refactoring never sleeps, so we do it again and again and again to give us:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val valuableCustomers = reader
    .asLineSequence()
    .valuableCustomers()
    .toListSortedBy(CustomerData::score)

private fun Sequence&amp;lt;String&amp;gt;.valuableCustomers(): Sequence&amp;lt;CustomerData&amp;gt; =
    withoutHeader()
        .map(String::toCustomerData)
        .filter { it.score &amp;gt;= 10 }

fun Reader.asLineSequence() = buffered().lineSequence()

fun &amp;lt;T, R : Comparable&amp;lt;R&amp;gt;&amp;gt; Sequence&amp;lt;T&amp;gt;.toListSortedBy(selector: (T) -&amp;gt; R?) =
    sortedBy(selector)
        .toList()

fun Sequence&amp;lt;String&amp;gt;.withoutHeader() = drop(1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Helpfully the three new extracted functions look like they are more generally applicable, so we’ve made them public and can extract them into our library of handy extensions.&lt;/p&gt;

&lt;p&gt;This refactoring is taken from an example in &lt;em&gt;Java to Kotlin, A Refactoring Guidebook&lt;/em&gt;, by Nat Pryce and me, due to be published in 2021 by O’Reilly. 
If you like it, you can read more work in progress on &lt;a href=&quot;https://learning.oreilly.com/library/view/java-to-kotlin/9781492082262/&quot;&gt;O’Reilly Online Learning&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;PS - &lt;a href=&quot;https://twitter.com/ponzao&quot;&gt;Vesa Marttila&lt;/a&gt; points out that we are using a &lt;code&gt;Reader&lt;/code&gt; here without closing it.
The &lt;code&gt;Sequence&lt;/code&gt; returned by &lt;code&gt;Reader.asLineSequence()&lt;/code&gt; makes no attempt to close the &lt;code&gt;BufferedReader&lt;/code&gt;, even if it is read to the end.
I usually work on the principle that whoever creates a resource which might leak should dispose of it, but that isn’t the &lt;code&gt;BufferedReader&lt;/code&gt; in this case, as that doesn’t itself hold any resources. At some level, this code should probably be surrounded in a block like&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;FileReader(filename).use { reader -&amp;gt;
    ...
}
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>Inline Tiny Types With Validation</title>
   <link href="http://0.0.0.0:4000/inline-tiny-types.html"/>
   <updated>2020-11-22T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/inline-tiny-types</id>
   <content type="html">&lt;p&gt;It’s been a long time since my last post.
This is largely because my writing efforts have been directed towards a book!
Nat Pryce (co-author of the excellent &lt;a href=&quot;http://www.growing-object-oriented-software.com/&quot;&gt;GOOS&lt;/a&gt;) and I are hard at work on &lt;em&gt;Java to Kotlin, A Refactoring Guidebook&lt;/em&gt;, due to be published in 2021 by O’Reilly.
You can read our work in progress on &lt;a href=&quot;https://learning.oreilly.com/library/view/java-to-kotlin/9781492082262/&quot;&gt;O’Reilly Online Learning&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Nat and I are both fans of &lt;a href=&quot;https://darrenhobbs.com/2007/04/11/tiny-types/&quot;&gt;tiny-types&lt;/a&gt;.
The basic idea here is to have a separate type for individual domain concepts rather than just using (usually) Strings. So we might define &lt;code&gt;GivenName&lt;/code&gt; and &lt;code&gt;FamilyName&lt;/code&gt; types so that a &lt;code&gt;Customer&lt;/code&gt; can be&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Customer(
    val id: CustomerId,
    val givenName: GivenName,
    val familyName: FamilyName
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compared to raw strings, we can’t mix up the order of our given and family names when we create a customer, nor can we accidentally pass an &lt;code&gt;OrderId&lt;/code&gt; where we need a &lt;code&gt;CustomerId&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here’s a typical tiny type in Kotlin:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class GivenName(val value: String)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can imagine, tiny types are a bit of a pain in Java, where we have to define &lt;code&gt;equals&lt;/code&gt;, &lt;code&gt;hashCode&lt;/code&gt; and &lt;code&gt;toString&lt;/code&gt; by hand, but Kotlin helps them make economic sense.
For bonus points, we can even have our types behave like a &lt;code&gt;CharSequence&lt;/code&gt; (the closest interface to &lt;code&gt;String&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class FamilyName(val value: String): CharSequence by value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This lets us write, for example&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;familyName.isNotBlank()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;because &lt;code&gt;isNotBlank&lt;/code&gt; is helpfully defined on &lt;code&gt;CharSequence&lt;/code&gt; not &lt;code&gt;String&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;On the subject of non-blank-ness, it would be really helpful if we were prevented from creating a blank &lt;code&gt;CustomerId&lt;/code&gt;.
That would go a long way to avoiding the errors we get when functions are partial - only defined on some of their inputs (see &lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Failure is not an Option, Part 7 - Avoiding Failure&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;We can prevent the creation of an invalid &lt;code&gt;CustomerId&lt;/code&gt; by checking the value in an &lt;code&gt;init&lt;/code&gt; block.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class CustomerId(val value: String): CharSequence by value {
    init {
        require(value.isNotBlank())
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we may get an error when we try to create a &lt;code&gt;CustomerId&lt;/code&gt;, but if we have an instance, we can rely on the fact that it isn’t blank.&lt;/p&gt;

&lt;p&gt;Given how easy they are to write in Kotlin, about the only drawback with tiny types is we actually end up with 2 objects to represent one value.
That’s the initial &lt;code&gt;String&lt;/code&gt;, and the data class wrapper around the string.
The extra object probably consumes an extra 16 bytes these days, which is quite an overhead if we have a lot of wrapped strings.
Potentially worse is the issue of cache coherency, because the initial string was probably created in the bowels of some JDBC code and may end up a long way in memory from its wrapper.
So calling a method on a tiny type reference may involve fetching it into cache, and then the value that it is wrapping.&lt;/p&gt;

&lt;p&gt;Kotlin &lt;a href=&quot;https://kotlinlang.org/docs/reference/inline-classes.html&quot;&gt;Inline Classes&lt;/a&gt;, whilst still experimental, are aimed at removing this overhead.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline class GivenName(val value: String)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In most circumstances the compiler arranges for instances of inline classes to be passed around as just the single contained value, so that we don’t have the overhead of creating an extra wrapper instance.
This should be perfect for tiny types.&lt;/p&gt;

&lt;p&gt;There’s one major problem though, we can’t easily validate inline classes.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline class CustomerId(val value: String) {
    init { // Error: Inline class cannot have an initializer block
        require(value.isNotBlank())
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;init&lt;/code&gt; blocks are disallowed because Java code is permitted to call Kotlin methods that take inline classes, passing the base type (&lt;code&gt;String&lt;/code&gt; above).
In this case the &lt;code&gt;init&lt;/code&gt; block won’t have been called, so users of inline classes can’t know that validation will have been performed.
So &lt;code&gt;init&lt;/code&gt; blocks are disallowed.&lt;/p&gt;

&lt;p&gt;For the same reason the primary constructor must be public.
In fact, every route to validating an inline class is &lt;a href=&quot;https://discuss.kotlinlang.org/t/about-init-blocks-in-inline-classes/11824&quot;&gt;deliberately blocked&lt;/a&gt; because it might not have been taken when called from Java.&lt;/p&gt;

&lt;p&gt;If you have a pure-Kotlin codebase, or just only ever call down into Java rather than back into Kotlin, this is a  shame.
It would be really nice to use inline classes to implement validated tiny types.
Can we find a way to make this work?&lt;/p&gt;

&lt;p&gt;What we need to do is either make sure that calling &lt;code&gt;CustomerId(&quot;&quot;)&lt;/code&gt; throws an exception, or prevent callers from calling the &lt;code&gt;CustomerId(val value: String)&lt;/code&gt; at all, instead making them go through some factory which can perform pre-validation.&lt;/p&gt;

&lt;p&gt;We can’t throw an exception from the constructor because we can’t have an init block, but there is a sneaky way to achieve the second, at least for pure Kotlin code -
make the value another inline class.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline class CustomerId(private val __value: __DontMakeMe) {
    val value get(): String = __value.value
}

inline class __DontMakeMe(val value: String)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, in Kotlin, we can’t call the constructor with a &lt;code&gt;String&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val id = CustomerId(&quot;42&quot;) // Type mismatch: inferred type is String but __DontMakeMe was expected
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We &lt;em&gt;can&lt;/em&gt; still call it, but there’s enough warning that we are subverting things:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val id = CustomerId(__DontMakeMe(&quot;42&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can create a factory function to validate a &lt;code&gt;String&lt;/code&gt; and create a  &lt;code&gt;CustomerId&lt;/code&gt; with it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun customerIdOf(s: String): CustomerId? =
    when {
        s.isNotBlank() -&amp;gt; CustomerId(__DontMakeMe(s))
        else -&amp;gt; null
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Looking at the bytecode, we end up calling a static ‘constructor’ function for both &lt;code&gt;CustomerId&lt;/code&gt; and &lt;code&gt;__DontMakeMe&lt;/code&gt; here, but both just check that their parameter is not null.&lt;/p&gt;

&lt;p&gt;I’ve chosen to return a nullable &lt;code&gt;CustomerId?&lt;/code&gt; from &lt;code&gt;customerIdOf&lt;/code&gt; so that callers know the call might fail, rather than having to read the code or documentation to see that it might throw an exception.&lt;/p&gt;

&lt;p&gt;Inline classes can implement interfaces, although not through delegation at present.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline class FamilyName(private val __value: __DontMakeMe): CharSequence {
    val value get(): String = __value.value

    override val length get() = value.length

    override fun get(index: Int) = value.get(index)

    override fun subSequence(startIndex: Int, endIndex: Int) =
        value.subSequence(startIndex, endIndex)
}

fun familyNameOf(s: String): FamilyName? =
    when {
        s.isNotBlank() -&amp;gt; FamilyName(__DontMakeMe(s))
        else -&amp;gt; null
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can also define &lt;code&gt;toString&lt;/code&gt; in order to mask sensitive information&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline class CardNumber(private val __value: __DontMakeMe) {
    val value get(): String = __value.value

    override fun toString() = &quot;************&quot; + value.substring(12)
}

fun cardNumberOf(s: String): CardNumber? =
    when {
        s.length == 16 &amp;amp;&amp;amp; s.all(Char::isDigit) -&amp;gt; CardNumber(__DontMakeMe(s))
        else -&amp;gt; null
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As I’ve said, this is a subversion of the inline class initialisation rules and won’t be safe if you accept calls in from Java.
I’m also not sure how marshalling technologies like Jackson or kotlinx.serialisation will interact with the technique.
For pure Kotlin codebases though I think it’s worth a try, as tiny types can significantly improve the readability and safety of our code.&lt;/p&gt;

&lt;p&gt;Come back soon, because I’ll present a tiny tiny types framework using phantom types to reduce the amount of boilerplate code required.&lt;/p&gt;

&lt;p&gt;Postscript - there is some discussion of other ways to achieve validation on the &lt;a href=&quot;https://www.reddit.com/r/Kotlin/comments/jzevz4/inline_tiny_types_with_validation/&quot;&gt;reddit discussion&lt;/a&gt;.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Fun With Maps Part 2</title>
   <link href="http://0.0.0.0:4000/fun-with-maps-part-2.html"/>
   <updated>2019-07-02T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/fun-with-maps-part-2</id>
   <content type="html">&lt;h2 id=&quot;recap&quot;&gt;Recap&lt;/h2&gt;

&lt;p&gt;In the &lt;a href=&quot;fun-with-maps-part-1.html&quot;&gt;previous episode&lt;/a&gt;, we looked at parsing a log file. We initially used data classes to represent the different types of events that we saw, but found that they could be clumsy when representing type hierarchies, and we had to fall back on reflection in order to select properties specified by strings.&lt;/p&gt;

&lt;p&gt;In contrast using maps to represent the data was (in this instance) less awkward, and they made it easy to select properties by name. Whilst I at least missed the reassurance that properties would be present and a given type that strong typing gave us, introducing a phantom type and extension properties allowed me to regain some of that confidence in a gradual way. I called the technique Phantom-typed PropertySets, but I’m hoping that someone else has given the technique a better name.&lt;/p&gt;

&lt;p&gt;So we have a way to alleviate some of the loose-typing problems of maps. What can we do to make data classes more convenient? In particular to allow us access to properties in a dynamic way like we can with maps?&lt;/p&gt;

&lt;h2 id=&quot;accessing-properties-with-reflection&quot;&gt;Accessing properties with reflection&lt;/h2&gt;

&lt;p&gt;We saw that we can use reflection access a the value of a Kotlin property by name. In short&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Suppress(&quot;UNCHECKED_CAST&quot;)
private fun Any.propertyValue(name: String): Any? =
    (this::class.memberProperties as Collection&amp;lt;KProperty1&amp;lt;Any, Any?&amp;gt;&amp;gt;).find {
        it.name == name
    }?.get(this)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That nasty cast is a result of the &lt;code&gt;out&lt;/code&gt; variance of &lt;code&gt;KClass&lt;/code&gt; - the less said about it the better. Let’s see it working.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Person(val firstName: String, val lastName: String)

class PropertyValueTests() {

    val person = Person(&quot;Fred&quot;, &quot;Flintstone&quot;)

    @Test fun tests() {
        assertEquals(&quot;Fred&quot;, person.propertyValue(&quot;firstName&quot;))
        assertNull(person.propertyValue(&quot;dob&quot;))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compared to Java reflection, that’s pretty convenient already. Could we do better? Could we just treat our data object &lt;em&gt;as&lt;/em&gt; a map?&lt;/p&gt;

&lt;p&gt;We would be on the right lines if we can get the following to work.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ObjectToMapTests() {

    val person = Person(&quot;Fred&quot;, &quot;Flintstone&quot;)
    val map = person.asPropertyMap()

    @Test fun tests() {
        assertEquals(&quot;Fred&quot;, map[&quot;firstName&quot;])
        assertNull(map[&quot;dob&quot;])

        assertEquals(2, map.size)
        assertEquals(setOf(&quot;firstName&quot;, &quot;lastName&quot;), map.keys)
        assertEquals(listOf(&quot;Fred&quot;, &quot;Flintstone&quot;), map.values)

        // etc
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;spaceblanket&quot;&gt;SpaceBlanket&lt;/h2&gt;

&lt;p&gt;If you fancy a challenge, go ahead and write your own implementation of &lt;code&gt;asPropertyMap&lt;/code&gt;. It’s an interesting task, and you may well make different trade-offs than I did.&lt;/p&gt;

&lt;p&gt;This was what I came up with.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun Any.asPropertyMap(): Map&amp;lt;String, Any?&amp;gt; = SpaceBlanket(this)

internal class SpaceBlanket(private val thing: Any) : Map&amp;lt;String, Any?&amp;gt; {

    override val entries: Set&amp;lt;Map.Entry&amp;lt;String, Any?&amp;gt;&amp;gt;
        get() = keys.map { AbstractMap.SimpleImmutableEntry(it, get(it)) }.toSet()

    override val keys by lazy { properties.filter { it.visibility == KVisibility.PUBLIC }.map { it.name }.toSet() }

    override val size: Int get() = keys.size

    override val values: Collection&amp;lt;Any?&amp;gt;
        get() = keys.map { this[it] }

    override fun containsKey(key: String) = keys.contains(key)

    override fun containsValue(value: Any?) = values.contains(value)

    override fun get(key: String): Any? = properties.firstOrNull { it.name == key }?.get(thing)

    override fun isEmpty() = size == 0

    override fun equals(other: Any?) = when (other) {
        is SpaceBlanket -&amp;gt; this.entries == other.entries
        is Map&amp;lt;*, *&amp;gt; -&amp;gt; other == this
        else -&amp;gt; false
    }

    // copied from AbstractMap
    override fun hashCode(): Int {
        var h = 0
        val i = entries.iterator()
        while (i.hasNext())
            h += i.next().hashCode()
        return h
    }

    override fun toString() = HashMap(this).toString()

    @Suppress(&quot;UNCHECKED_CAST&quot;)
    private val properties by lazy {
        thing::class.memberProperties as Collection&amp;lt;KProperty1&amp;lt;Any, Any?&amp;gt;&amp;gt; // nasty cast due to out variance of thing::class
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I’ve published this on &lt;a href=&quot;https://github.com/dmcg/spaceblanket&quot;&gt;GitHub&lt;/a&gt; as a proof of concept. There are lots more features you could reasonably want, in particular recursively yielding maps for all non-primitive properties, but it is still pretty handy. We can go back to the &lt;code&gt;filterFile&lt;/code&gt; example from Part 1 and write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun filterFile(file: File, propertyName: String, propertyValue: String) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntry() }
        .filter { it.asPropertyMap()[propertyName].toString() == propertyValue }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;or to dump all the properties of a Kotlin object with their values&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun Any.dumped() = println(
    this
        .asPropertyMap()
        .entries
        .joinToString(&quot;,&quot;) { &quot;${it.key} = ${it.value}&quot; }
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or check a subset of the properties of an object in one go&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun check(entry: IPEntry) {
    val expected = mapOf(&quot;index&quot; to &quot;index #0&quot;, &quot;interfaceName&quot; to &quot;VLINK1&quot;)
    val relevantProperties: Map&amp;lt;String, Any?&amp;gt; = entry
        .asPropertyMap()
        .entries
        .filter { it.key in expected.keys }
        .map { it.key to it.value }
        .toMap()
    assertEquals(expected, relevantProperties)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Converting to a map isn’t the only way to solve these sorts of problems, but the chances are that you &lt;em&gt;can&lt;/em&gt; work out how to solve them with a map, so it may well be a good start.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Data classes are a really nice feature of Kotlin, and should be your default choice for representing data, but they have limitations.&lt;/p&gt;

&lt;p&gt;If you have unknown data, a heavily subtyped data model, or need dynamic access to properties, maps may be a better choice. You can bring some gradual typing to your maps using Phantom-typed PropertySets.&lt;/p&gt;

&lt;p&gt;If you choose data classes and find that you occasionally need map-like access, SpaceBlanket or something like it can retrofit a map interface to standard Kotlin objects.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href=&quot;http://natpryce.com&quot;&gt;Nat Pryce&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/_fletchr&quot;&gt;Rob Fletcher&lt;/a&gt; and &lt;a href=&quot;http://tutteli.ch&quot;&gt;Robert Stoll&lt;/a&gt; for providing feedback on this article.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Fun With Maps Part 1</title>
   <link href="http://0.0.0.0:4000/fun-with-maps-part-1.html"/>
   <updated>2019-06-30T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/fun-with-maps-part-1</id>
   <content type="html">&lt;p&gt;I’ve been listening to &lt;a href=&quot;https://clojuredesign.club/&quot;&gt;an&lt;/a&gt; (and &lt;a href=&quot;https://lispcast.com/category/podcast/&quot;&gt;another&lt;/a&gt;) excellent podcast by Clojure programmers recently and learned that nobody builds classes in Clojure; and certainly not to represent data. Instead they populate maps for all the uses where Kotlin developers would reach for a data class.&lt;/p&gt;

&lt;p&gt;I’ve got very used to data classes and like them a lot, but there are certainly situations in which they don’t shine. Today I’m going to look using maps instead.&lt;/p&gt;

&lt;h2 id=&quot;the-brief&quot;&gt;The Brief&lt;/h2&gt;

&lt;p&gt;Let’s say that we want to parse a log file into semantic representations of different sorts of errors. Here’s one I borrowed from &lt;a href=&quot;https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.hald001/exmlogfile.htm&quot;&gt;IBM&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;03/22 08:51:01 INFO   :.main: *************** RSVP Agent started ***************
03/22 08:51:01 INFO   :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
03/22 08:51:01 INFO   :.main: Using log level 511
03/22 08:51:01 INFO   :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
03/22 08:51:01 INFO   :..settcpimage: Associate with TCP/IP image name = TCPCS
03/22 08:51:02 INFO   :..reg_process: registering process with the system
03/22 08:51:02 INFO   :..reg_process: attempt OS/390 registration
03/22 08:51:02 INFO   :..reg_process: return from registration rc=0
03/22 08:51:06 TRACE  :...read_physical_netif: Home list entries¢ returned = 7
03/22 08:51:06 INFO   :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
03/22 08:51:06 INFO   :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
03/22 08:51:06 INFO   :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
03/22 08:51:06 INFO   :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
03/22 08:51:06 INFO   :....mailslot_create: creating mailslot for timer
03/22 08:51:06 INFO   :...mailbox_register: mailbox allocated for timer
03/22 08:51:06 INFO   :.....mailslot_create: creating mailslot for RSVP
03/22 08:51:06 INFO   :....mailbox_register: mailbox allocated for rsvp
03/22 08:51:06 INFO   :.....mailslot_create: creating mailslot for RSVP via UDP
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;data-classes&quot;&gt;Data Classes&lt;/h2&gt;

&lt;p&gt;If we can get past wondering why some developer decided that it was worth outputting the day and month but not the year of each entry, we would probably decide to represent each entry with a data class&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class LogEntry(val timestamp: Instant, val level: String, val message: String)

fun String.toLogEntry() = LogEntry(
    substring(0, 15).toInstantSomehow(),
    substring(16, 23).trim(),
    substring(24).trim()
)

fun showRecentAddresses(file: File) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntry() }
        .filter { it.timestamp.isAfter(lastTuesday) }
        .filter { it.message.contains(&quot;interface .*? has address&quot;.toRegex()) }
        .map { it.message.split(&quot;,&quot;)[1] }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That’s fine for a one-off analysis, but no good deed goes unpunished. Soon we’re asked to write a suite of analysis software so that the rest of the team can get on with not writing the year into timestamps. We end up with data classes for the different types of log lines that we know how to parse, with an interface for the common data in every line.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;interface LogEntry {
    val timestamp: Instant
    val level: String
    val loggerName: String
    val message: String
}

data class BasicEntry(
    override val timestamp: Instant,
    override val level: String,
    override val loggerName: String,
    override val message: String
) : LogEntry

private val lineParser =
    &quot;&quot;&quot;^(?&amp;lt;timestamp&amp;gt;.{14}) (?&amp;lt;level&amp;gt;.*?) *?:\.+(?&amp;lt;name&amp;gt;.*?): (?&amp;lt;message&amp;gt;.*)$&quot;&quot;&quot;.toRegex()

fun String.toBasicEntry() = lineParser.find(this)?.groups?.let { groups -&amp;gt;
    BasicEntry(
        timestamp = groups[&quot;timestamp&quot;]?.value?.toInstantSomehow()
            ?: error(&quot;no timestamp in line $this&quot;),
        level = groups[&quot;level&quot;]?.value
            ?: error(&quot;no level in line $this&quot;),
        loggerName = groups[&quot;name&quot;]?.value
            ?: error(&quot;no logger name in line $this&quot;),
        message = groups[&quot;message&quot;]?.value
            ?: error(&quot;no messagein line $this&quot;)
    )
} ?: error(&quot;Could not parse as BasicEntry $this&quot;)

data class IPEntry(
    override val timestamp: Instant,
    override val level: String,
    override val loggerName: String,
    override val message: String,
    val index: Int,
    val interfaceName: String,
    val address: String
) : LogEntry

fun BasicEntry.toIPEntry(): IPEntry? =
    if (loggerName == &quot;read_physical_netif&quot;)
        IPEntry(timestamp, level, loggerName, message, SOMECODE(), SOMECODE(), SOMECODE())
    else
        null

data class RegProcessEntry(
    override val timestamp: Instant,
    override val level: String,
    override val loggerName: String,
    override val message: String
) : LogEntry

fun BasicEntry.toRegProcessEntry(): RegProcessEntry? =
    if (loggerName == &quot;reg_process&quot;) SOMECODE() else null

data class MailslotCreateEntry(
    override val timestamp: Instant,
    override val level: String,
    override val loggerName: String,
    override val message: String,
    val createdFor: String,
    val createdVia: String?
) : LogEntry

fun BasicEntry.toMailSlotCreateEntry(): MailslotCreateEntry? =
    if (loggerName == &quot;mailslot_create&quot;) SOMECODE() else null

val converters = listOf&amp;lt;(BasicEntry) -&amp;gt; LogEntry?&amp;gt;(
    BasicEntry::toIPEntry,
    BasicEntry::toRegProcessEntry,
    BasicEntry::toMailSlotCreateEntry
    //...
)

fun String.toLogEntry(): LogEntry {
    val rawEntry = this.toBasicEntry()
    return converters.asSequence()
        .mapNotNull { it(rawEntry) }
        .firstOrNull()
        ?: rawEntry
}

fun showRecentAddresses(file: File) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntry() }
        .filterIsInstance&amp;lt;IPEntry&amp;gt;()
        .filter { it.timestamp.isAfter(lastTuesday) }
        .map { &quot;${it.interfaceName} : ${it.address}&quot; }
        .forEach(::println)
}

// etc
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This isn’t the only formulation of this data with data classes, and I’m not sure that it’s the best, but it is the sort of thing that we end up with in these situations. And it is, well, horrible, largely because you can’t inherit from a data classes. We could have made &lt;code&gt;BasicEntry&lt;/code&gt; the only property of &lt;code&gt;LogEntry&lt;/code&gt; to remove some duplication, or make &lt;code&gt;BasicEntry&lt;/code&gt; the envelope containing a typed contents of the parsed payloads, but it’s all rather icky because of the inheritance limitation of data classes.&lt;/p&gt;

&lt;p&gt;There is another problem with data classes - we don’t have (easy) runtime access to their properties. Which is a problem because now the ops people would like us to use our technology to filter lines that contain a given property value. They are happy to look in our source for the names of the properties, but don’t want to be recompiling Kotlin every time they want a change, so we need to take the property name and value on the command-line.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;java -jar filter-log.jar file.log interfaceName=VLINK1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So we set to and write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun filterFile(file: File, propertyName: String, propertyValue: String) =
    file.useLines { lines -&amp;gt;
        lines.map { it.toLogEntry() }
            .filter { it.hasProperty(propertyName, propertyValue) }
            .forEach(::println)
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;How do we write &lt;code&gt;LogEntry.hasProperty&lt;/code&gt; without lots of tables or trying to keep code up to date? Reflection is the answer, but it has just taken me 30 minutes to get the following to compile&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Suppress(&quot;UNCHECKED_CAST&quot;)
private fun Any.hasProperty(name: String, value: String): Boolean =
    (this::class as KClass&amp;lt;Any&amp;gt;).memberProperties.any {
        it.name == name &amp;amp;&amp;amp; it.get(this).toString() == value
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and even now it does it is relatively slow at runtime. Once we start mixing runtime selection with data classes we find all sorts of things that we have to use reflection to solve - we can’t even ask a data class for the number of its properties without reflection (&lt;a href=&quot;https://github.com/LunarWatcher/KClassUnpacker/&quot;&gt;or a compiler plugin&lt;/a&gt;). Serialising to and from JSON? We have clever libraries that hide it but it’s all refection underneath.&lt;/p&gt;

&lt;p&gt;Now compared to Java, data classes are a real boon. In Kotlin they should certainly be your default choice for representing data as objects. But even when I offered data classes as a solution to a Clojure developer, he said that he would generally stick with maps. Why is this?&lt;/p&gt;

&lt;h2 id=&quot;maps&quot;&gt;Maps&lt;/h2&gt;

&lt;p&gt;Let’s have a look at solving the same problem with maps.&lt;/p&gt;

&lt;p&gt;First the simple case&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun String.toLogMap(): Map&amp;lt;String, Any?&amp;gt; = mapOf(
    &quot;timestamp&quot; to substring(0, 15).toInstantSomehow(),
    &quot;level&quot; to substring(16, 23).trim(),
    &quot;rawMessage&quot; to substring(24).trim()
)

fun showRecentAddresses(file: File) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogMap() }
        .filter { (it[&quot;timestamp&quot;] as Instant).isAfter(lastTuesday) }
        .filter { (it[&quot;rawMessage&quot;] as String).contains(&quot;interface .*? has address&quot;.toRegex()) }
        .map { (it[&quot;rawMessage&quot;] as String).split(&quot;,&quot;)[1] }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmmm, those casts are a bit ugly. They wouldn’t be there in Clojure of course, and we can do better in Kotlin as we’ve given up type safety anyway&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Suppress(&quot;EXTENSION_SHADOWED_BY_MEMBER&quot;)
inline fun &amp;lt;reified R&amp;gt; Map&amp;lt;String, Any?&amp;gt;.get(key: String) = get(key) as R

fun showRecentAddresses(file: File) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogMap() }
        .filter { it.get&amp;lt;Instant&amp;gt;(&quot;timestamp&quot;).isAfter(lastTuesday) }
        .filter { it.get&amp;lt;String&amp;gt;(&quot;rawMessage&quot;).contains(&quot;interface .*? has address&quot;.toRegex()) }
        .map { it.get&amp;lt;String&amp;gt;(&quot;rawMessage&quot;).split(&quot;,&quot;)[1] }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a bit worse than the data class version, why would we give up the type safety that we had? Well the equivalent of the more developed example is quite a bit simpler because we don’t have to try to bend data classes to our will.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;typealias LogEntryProperties = Map&amp;lt;String, Any?&amp;gt;

val lineParser = &quot;&quot;&quot;^(?&amp;lt;timestamp&amp;gt;.{14}) (?&amp;lt;level&amp;gt;.*?) *?:\.+(?&amp;lt;name&amp;gt;.*?): (?&amp;lt;message&amp;gt;.*)$&quot;&quot;&quot;.toRegex()

fun String.extractBasicProperties(): LogEntryProperties =
    lineParser.find(this)?.groups?.let { groups -&amp;gt;
        mapOf(
            &quot;timestamp&quot; to (groups[&quot;timestamp&quot;]?.value?.toInstantSomehow() ?: error(&quot;no timestamp in line $this&quot;)),
            &quot;level&quot; to (groups[&quot;level&quot;]?.value ?: error(&quot;no level in line $this&quot;)),
            &quot;loggerName&quot; to (groups[&quot;name&quot;]?.value ?: error(&quot;no logger name in line $this&quot;)),
            &quot;message&quot; to (groups[&quot;message&quot;]?.value ?: error(&quot;no messagein line $this&quot;))
        )
    } ?: error(&quot;Could not extract properties from $this&quot;)


fun LogEntryProperties.withIPProperties(): LogEntryProperties =
    if (get&amp;lt;String&amp;gt;(&quot;loggerName&quot;) == &quot;read_physical_netif&quot;)
        this + mapOf(
            &quot;interface/index&quot; to SOMECODE(),
            &quot;interface/name&quot; to SOMECODE(),
            &quot;interface/address&quot; to SOMECODE()
        )
    else
        this

fun LogEntryProperties.withRegProcessProperties(): LogEntryProperties = SOMECODE()

fun LogEntryProperties.withMailSlotCreateProperties(): LogEntryProperties = SOMECODE()

val extractors = listOf(
    LogEntryProperties::withIPProperties,
    LogEntryProperties::withRegProcessProperties,
    LogEntryProperties::withMailSlotCreateProperties
)

fun String.toLogEntryProperties(): LogEntryProperties =
    extractors.fold(this.extractBasicProperties()) { acc, f -&amp;gt; f(acc) }

fun showRecentAddresses(file: File) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntryProperties() }
        .filter { it.containsKey(&quot;interface/index&quot;) }
        .filter { it.get&amp;lt;Instant&amp;gt;(&quot;timestamp&quot;).isAfter(lastTuesday) }
        .map { &quot;${it[&quot;interface/name&quot;]} : ${it[&quot;interface/address&quot;]}&quot; }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(Notice that we have added a namespace prefix to the property names - this isn’t strictly necessary but helps to avoid collisions in the event that more than one extractor matches a line.)&lt;/p&gt;

&lt;p&gt;Because data is just stored in a map we don’t have to define data classes to match its shape, but we have lost the type safety that the properties of the data class were giving us, both with respect to their names and types. The data class implementation will almost certainly be faster, because reading a property is a single method call and field access, and more space efficient, because we won’t be creating sparse map structures.  In short, data classes should probably be your default representation, even though they can be clumsy.&lt;/p&gt;

&lt;p&gt;But what about that additional requirement of filtering by properties on the command line? That’s where the maps shine&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun filterFile(file: File, propertyName: String, propertyValue: String) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntryProperties() }
        .filter { it[propertyName].toString() == propertyValue } // this is now just a map lookup - no reflection
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Not having to deal with reflection is really nice here, the map really is first class data, whereas the data class makes you jump through reflective hoops.&lt;/p&gt;

&lt;p&gt;So, data classes are good for some things, maps are good for others. Can we meet in the middle?&lt;/p&gt;

&lt;p&gt;We can, but you have to decide whether your fundamental representation is going to be data classes, and you just wish that they behaved more like maps sometimes, or you are going to start from maps, and wouldn’t it be nice if they could be more type safe? As the maps version is still fresh, let’s look at making maps more type safe.&lt;/p&gt;

&lt;h2 id=&quot;propertyset&quot;&gt;PropertySet&lt;/h2&gt;

&lt;p&gt;I have a technique for making maps more type-safe that I haven’t tried in anger, but I think has promise. I’m tentatively calling it the Phantom-typed PropertySet.&lt;/p&gt;

&lt;p&gt;The problem it (partially) solves is that of passing information about what properties a map contains at compile time. Without this we run into the partial function problem described in &lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Avoiding Failure&lt;/a&gt; - functions that take a &lt;code&gt;Map&amp;lt;String, Any?&amp;gt;&lt;/code&gt; can fail at runtime because the actual map passed does not have the required keys (or they are the wrong type).&lt;/p&gt;

&lt;p&gt;My plan is to parameterise &lt;code&gt;Map&amp;lt;String, Any?&amp;gt;&lt;/code&gt; with another type that prevents them from all looking alike. Let’s call that type &lt;code&gt;PropertySet&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;interface PropertySet&amp;lt;out T&amp;gt; : Map&amp;lt;String, Any?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can implement &lt;code&gt;PropertySet&lt;/code&gt;s by delegating to another map&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MapPropertySet&amp;lt;out T&amp;gt;(private val delegate: Map&amp;lt;String, Any?&amp;gt;)
    : PropertySet&amp;lt;T&amp;gt;,
      Map&amp;lt;String, Any?&amp;gt; by delegate {
    constructor(vararg properties: Pair&amp;lt;String, Any&amp;gt;) : this(mapOf(*properties))
}

fun &amp;lt;T&amp;gt; propertySetOf(vararg properties: Pair&amp;lt;String, Any&amp;gt;): PropertySet&amp;lt;T&amp;gt; =
    MapPropertySet(*properties)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and provide a function to combine them like maps&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;operator fun &amp;lt;T&amp;gt; PropertySet&amp;lt;T&amp;gt;.plus(other: PropertySet&amp;lt;T&amp;gt;): PropertySet&amp;lt;T&amp;gt; =
    MapPropertySet(
        (this.entries + other.entries).map { entry -&amp;gt; entry.key to entry.value }
            .toMap())

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let’s look at our log parsing example. A &lt;code&gt;PropertySet&lt;/code&gt; needs a type, but the type doesn’t have to do anything. An empty interface will do fine.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;interface Base
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can parse the basic log information into a &lt;code&gt;PropertySet&amp;lt;Base&amp;gt;&lt;/code&gt; just like we did for plain maps&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun String.extractBasicProperties(): PropertySet&amp;lt;Base&amp;gt; =
    lineParser.find(this)?.groups?.let { groups -&amp;gt;
        propertySetOf&amp;lt;Base&amp;gt;(
            &quot;timestamp&quot; to (groups[&quot;timestamp&quot;]?.value?.toInstantSomehow()
                ?: error(&quot;no timestamp in line $this&quot;)),
            &quot;level&quot; to (groups[&quot;level&quot;]?.value
                ?: error(&quot;no level in line $this&quot;)),
            &quot;loggerName&quot; to (groups[&quot;name&quot;]?.value
                ?: error(&quot;no logger name in line $this&quot;)),
            &quot;message&quot; to (groups[&quot;message&quot;]?.value
                ?: error(&quot;no messagein line $this&quot;))
        )
    } ?: error(&quot;Could not extract properties from $this&quot;)

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let’s say that we need semantic access to the timestamp. We can provide that with an extension property on &lt;code&gt;PropertySet&amp;lt;Base&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val PropertySet&amp;lt;Base&amp;gt;.timeStamp get() = get&amp;lt;Instant&amp;gt;(&quot;timestamp&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That property allows access to, and knowledge of the type of, timestamp only when we have the right type of &lt;code&gt;PropertySet&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val aPropertySet: PropertySet&amp;lt;Base&amp;gt; = SOMECODE()
val timestamp: Instant = aPropertySet.timeStamp

val aDifferentPropertySet: PropertySet&amp;lt;Any&amp;gt; = SOMECODE()
// doesn't compile
// val nogo = aDifferentPropertySet.timeStamp
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we still have access to other properties with the unsafe-but-usefully-dynamic map interface&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val level = aPropertySet.get&amp;lt;String&amp;gt;(&quot;level&quot;)

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can do the same for our other ‘types’&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;interface IP : Base

val PropertySet&amp;lt;Base&amp;gt;.loggerName get() = get&amp;lt;String&amp;gt;(&quot;loggerName&quot;)

fun PropertySet&amp;lt;Base&amp;gt;.withIPProperties(): PropertySet&amp;lt;Base&amp;gt; =
    if (loggerName == &quot;read_physical_netif&quot;)
        this + propertySetOf(
            &quot;interface/index&quot; to SOMECODE(),
            &quot;interface/name&quot; to SOMECODE(),
            &quot;interface/address&quot; to SOMECODE()
        )
    else
        this

val PropertySet&amp;lt;IP&amp;gt;.name get() = get&amp;lt;String&amp;gt;(&quot;interface/name&quot;)
val PropertySet&amp;lt;IP&amp;gt;.address get() = get&amp;lt;String&amp;gt;(&quot;interface/address&quot;)

interface RegProcess

fun PropertySet&amp;lt;Base&amp;gt;.withRegProcessProperties(): PropertySet&amp;lt;Base&amp;gt; = SOMECODE()

interface MailSlotCreate

fun PropertySet&amp;lt;Base&amp;gt;.withMailSlotCreateProperties(): PropertySet&amp;lt;Base&amp;gt; = SOMECODE()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Parsing is the same as for the maps example&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val extractors = listOf(
    PropertySet&amp;lt;Base&amp;gt;::withIPProperties,
    PropertySet&amp;lt;Base&amp;gt;::withRegProcessProperties,
    PropertySet&amp;lt;Base&amp;gt;::withMailSlotCreateProperties
)

fun String.toLogEntryProperties(): PropertySet&amp;lt;Base&amp;gt; =
    extractors.fold(this.extractBasicProperties()) { acc, f -&amp;gt; f(acc) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the only thing missing to build &lt;code&gt;showRecentAddresses&lt;/code&gt; is the downcast from &lt;code&gt;PropertySet&amp;lt;Base&amp;gt;&lt;/code&gt; to &lt;code&gt;PropertySet&amp;lt;IP&amp;gt;&lt;/code&gt;. In order to do this we need to know that the map actually does have the properties that the &lt;code&gt;PropertySet&amp;lt;IP&amp;gt;&lt;/code&gt; extension properties imply. We can get away here with just checking that one of them is there.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Suppress(&quot;UNCHECKED_CAST&quot;)
fun PropertySet&amp;lt;Base&amp;gt;.asSetOfIP(): PropertySet&amp;lt;IP&amp;gt;? =
    if (containsKey(&quot;interface/index&quot;)) this as PropertySet&amp;lt;IP&amp;gt; else null
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and now &lt;code&gt;mapNotNull&lt;/code&gt; will conveniently cast and filter&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun showRecentAddresses(file: File) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntryProperties() }
        .mapNotNull { it.asSetOfIP() }
        .filter { it.timeStamp.isAfter(lastTuesday) } // it is PropertySet&amp;lt;IP&amp;gt; now
        .map { &quot;${it.name} : ${it.address}&quot; }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and because we really are just dealing with maps, our previous &lt;code&gt;filterFile&lt;/code&gt; continues to work fine.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun filterFile(file: File, propertyName: String, propertyValue: String) = file.useLines { lines -&amp;gt;
    lines.map { it.toLogEntryProperties() }
        .filter { it[propertyName].toString() == propertyValue }
        .forEach(::println)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This technique of taking a map and tagging it with a type-erased but reconstructable marker, and synthesising properties based on the marker type, is a nice way to add gradual typing to a map-based data model. What if we want to go the other way round - represent a statically-typed model as a map? We’ll look at that in the &lt;a href=&quot;fun-with-maps-part-2.html&quot;&gt;next episode&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href=&quot;http://natpryce.com&quot;&gt;Nat Pryce&lt;/a&gt;, &lt;a href=&quot;https://twitter.com/_fletchr&quot;&gt;Rob Fletcher&lt;/a&gt; and &lt;a href=&quot;http://tutteli.ch&quot;&gt;Robert Stoll&lt;/a&gt; for providing feedback on this article.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Refactoring to Kotlin</title>
   <link href="http://0.0.0.0:4000/refactoring-to-kotlin.html"/>
   <updated>2019-06-20T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/refactoring-to-kotlin</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://natpryce.com&quot;&gt;Nat Pryce&lt;/a&gt; and I have been asked to run our popular Refactoring to Kotlin Workshop at KotlinConf 2019 in Copenhagen.&lt;/p&gt;

&lt;p&gt;If you are attending the conference but relatively new to the language it is an excellent way to get up to speed on the language and its idioms.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/refactoring-to/&quot;&gt;More Details&lt;/a&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 7 - Avoiding Failure</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-7.html"/>
   <updated>2019-06-19T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-7</id>
   <content type="html">&lt;p&gt;This is Part 7 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Today I’d like to talk about avoiding error handling.&lt;/p&gt;

&lt;p&gt;If I was cleverer than I am, this would have been the first part of this series. But I was seduced by the techniques of error handling and, as is often the case, not listening to what pain was telling me about my situation. It has taken 12 months of reading and thinking to realise what some people (hi Barry) were telling me a year ago. In my defence, I have not seen the advice in this post spelled out so directly, although I may just not have understood it when I saw it. My hope is that even if this is just another blog post saying the same thing as many others, it will increase the chances that people come to this information when they are ready to receive it.&lt;/p&gt;

&lt;p&gt;So&lt;/p&gt;

&lt;p&gt;As we’ve seen from the other posts in this series, handling errors is tedious and itself error-prone - and we could all do with less tedium and fewer errors. Exceptions are less tedious in code than other techniques, but as they allow us to sweep possible problems under the carpet, we either get less reliable code, or the tedium of lifting a lot of carpets. Result types are tedious in code, but potentially more reliable. Checked exceptions were a valiant effort to get the best of both worlds, but in the end foundered on the rock of first-class functions.&lt;/p&gt;

&lt;p&gt;Errors are particularly pernicious in code because they are transitive. If a function relies on code that can fail then it either has to have a strategy for succeeding despite the failure of its compatriot, or it is itself subject to failure. Pretty soon any moderately complex functionality has a combinatorial explosion of ways that it can fail. We then end up adding code to reason with the possible errors just so that a function can fail with a error that makes sense to its callers. And that error handling code itself is subject to errors!&lt;/p&gt;

&lt;p&gt;If we rely on exceptions for our error handling then the net effect is that most complex code paths can effectively throw any exception, and without checked exceptions we have no easy way to work out which. And even if we do work it out, then just swapping out one function for another can invalidate the analysis. Exactly the same thing is true for a Result type but with more complicated return types and control flow. (Actually there is another approach using sealed classes to represent errors within a bounded context. We’ll cover that in another post - it can reduce the types of errors that have to be considered, but doesn’t change their transitive nature.)&lt;/p&gt;

&lt;p&gt;So what do we do? Mostly we suck it up. We catch exceptions at the top level and log and return an error, and/or we accept that every non-trivial function will return &lt;code&gt;Either&amp;lt;R, Exception&amp;gt;&lt;/code&gt; and handle &lt;em&gt;that&lt;/em&gt; at the top level in the same way. At some boundaries we try to deal with errors we know might happen in a sensible way, and then we run our systems and add code to deal with the other problems that we actually see.&lt;/p&gt;

&lt;p&gt;I don’t think that this can ever change completely, but it would be good if it applied to less of our codebase. Our aim should be to reduce the number of functions that can fail. If in particular we can do that for lower-level functions, then the higher level functions that call them will also become less subject to failure, which in time should significantly reduce the proportion of functions that have to consider error cases at all. The boundary of code that is always subject to failure will rise up through the layers. This seems like a far better outcome than my previous experience, which was that learning better error handling techniques just allowed me to tolerate the pain all over, instead of encouraging me to expand the pain-free zones.&lt;/p&gt;

&lt;p&gt;With the aim of reducing with number of our functions that can fail in mind, what are the reasons that a function can fail?&lt;/p&gt;

&lt;h2 id=&quot;type-of-errors&quot;&gt;Type of Errors&lt;/h2&gt;

&lt;p&gt;Here are some basic categories of errors that can occur in a program.&lt;/p&gt;

&lt;h3 id=&quot;general-environmental-failures&quot;&gt;General Environmental Failures&lt;/h3&gt;

&lt;p&gt;These are things that can just happen, but shouldn’t if things are not very badly broken. We might run out of memory, or find that a referenced method is not present because required libraries are not linked. All bets are off in these circumstances - they are represented by throwing a subclass of &lt;code&gt;Error&lt;/code&gt; and we should probably just let the program die.&lt;/p&gt;

&lt;h3 id=&quot;external-failures&quot;&gt;External Failures&lt;/h3&gt;

&lt;p&gt;Generally represented on the JVM by &lt;code&gt;IOException&lt;/code&gt; - these represent a failure external to our program. Maybe a function tried to read from a file that no longer exists, or write to a network socket that has died.&lt;/p&gt;

&lt;p&gt;In practice the prevalence of external errors varies widely even when they can occur in principle. Both reading from an open file and writing to a socket &lt;em&gt;could&lt;/em&gt; fail, but files on our local filesystem are rarely deleted while we are reading them. In contrast we should assume that any network call will fail at some point. If a function is likely to fail in this way, we need to plan for it. If we need to plan for it, it would be nice if we had been told that it was likely to happen, either by declaring a thrown exception or returning a result type.&lt;/p&gt;

&lt;p&gt;Also in practice, functions that can fail with &lt;code&gt;IOException&lt;/code&gt; are generally ‘impure’ in a functional programming sense - their result doesn’t just depend on the value of their arguments. I’ll have to talk about this topic another time, but one way to deal with this impurity is to push such functions to the edges of our systems. If we manage to push it to the top edge, then most of our system layers will not have to deal with any such error, but this is a hard trick to pull off.&lt;/p&gt;

&lt;p&gt;For now then let’s just assume that many, but by no means all, of our functions will be subject to failure with an &lt;code&gt;IOException&lt;/code&gt;, either because they read from external systems, or invoke functions that are themselves subject to failure with an &lt;code&gt;IOException&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;partial-functions&quot;&gt;Partial Functions&lt;/h3&gt;

&lt;p&gt;The other common reason that a function may not be able to return normally (where abnormally includes returning an &lt;code&gt;Error&lt;/code&gt; as part of a &lt;code&gt;Result&lt;/code&gt; type) is that it is only able to give an output for a restricted range of its inputs - a partial function. A good example from previous episodes was&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Int = SOMECODE()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is only able to return an &lt;code&gt;Int&lt;/code&gt; for a special subset of all strings that might be passed in. An even more common example is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Array&amp;lt;T&amp;gt; {
    operator fun get(index: Int): T = SOMECODE()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Array indexing can only succeed if the index is contained in the array, which (in most but not all languages) cannot be known at compile time.&lt;/p&gt;

&lt;p&gt;If a partial function is passed an input for which it is undefined it is polite for it to let us know - generally by throwing an exception, returning &lt;code&gt;null&lt;/code&gt;, or returning an error code.&lt;/p&gt;

&lt;p&gt;It is partial functions that I’d like to think about today, as in most systems they represent the majority of the errors that can occur.&lt;/p&gt;

&lt;h2 id=&quot;healing-partial-functions&quot;&gt;Healing Partial Functions&lt;/h2&gt;

&lt;p&gt;As this is a Kotlin post, it’s worth noting every function that takes a reference and cannot cope with it being null is a partial function. Kotlin allows us to make those functions total by specifying that they cannot be invoked with a null argument.&lt;/p&gt;

&lt;p&gt;Can we heal partial functions by changing the type of their parameters in other cases?&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5&lt;/a&gt; I looked at various implementations of&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun addAsInts(s1: String, s2: String, s3: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf {
    Integer.parseInt(s1) + Integer.parseInt(s2) + Integer.parseInt(s3)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Adding integers represented as strings is a partial function because it is only defined where each of its inputs can be interpreted as an integer. Here it is made a total function by expanding its result type so that we can return a failure result in these cases - but now all callers have to deal with this result rather than a plain old &lt;code&gt;Int&lt;/code&gt;. As Part 5 showed, that can lead to some pretty cryptic code, especially when we come to combining results from several partial functions.&lt;/p&gt;

&lt;p&gt;Now the example was chosen to illustrate how to combine results, but we can also solve the partial function problem by simply changing the signature.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun add(i1: Int, i2: Int, i3: Int): Int = i1 + i2 + i3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the function is total again, and we don’t have to pollute our calling code with error handling.&lt;/p&gt;

&lt;p&gt;Where the data is naturally a string in the first place (typed by the user perhaps) then we are going to have to convert to &lt;code&gt;Int&lt;/code&gt; somewhere. We &lt;em&gt;could&lt;/em&gt; do that just before we need to interpret it, but that makes every function above it in the call stack either partial or subject to the errors in the conversion. So in this case we would almost certainly convert to &lt;code&gt;Int&lt;/code&gt; as soon as possible, especially as the earlier we convert the more context we have available to report errors. The alternative is trying to recreate this context from an exception or result code propagated from several layers down.&lt;/p&gt;

&lt;p&gt;In other cases though it’s easy to underestimate how much simpler this makes things and pass down strings that represent &lt;code&gt;URI&lt;/code&gt;’s, or &lt;code&gt;File&lt;/code&gt;s or &lt;code&gt;DateTime&lt;/code&gt;s and hence make the functions that interpret them partial.&lt;/p&gt;

&lt;p&gt;With a bit of work many otherwise partial functions can be made total. Integer division, for example, can fail.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;// throws ArithmeticException if count is 0
fun average(sum: Int, count: Int) = sum / count
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can fix this &lt;code&gt;average&lt;/code&gt; by introducing a type to represent a &lt;code&gt;NonZeroInt&lt;/code&gt; and using it as a parameter. This makes the function total - it is now defined for all possible (runtime) values of its parameters.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class NonZeroInt(val value: Int) {
    init {
        require(value != 0)
    }
}

fun average(sum: Int, count: NonZeroInt) = sum / count

// Can't fail because divisor.value can never be 0
operator fun Int.div(divisor: NonZeroInt) = this / divisor.value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Similarly, many List operations can fail on an empty list, but be made total on a non-empty list.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class NonEmptyList&amp;lt;T&amp;gt;(private val wrapped: List&amp;lt;T&amp;gt;) :
    List&amp;lt;T&amp;gt; by wrapped {
    init {
        require(wrapped.isNotEmpty())
        wrapped.first()
    }
}
&lt;/code&gt;&lt;/pre&gt;

</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 6 - What Should You Do While Waiting for the Standard Result Type</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-6.html"/>
   <updated>2019-06-16T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-6</id>
   <content type="html">&lt;p&gt;This is Part 6 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It has been over a year since I wrote Part 5, and quite a lot has happened in that time. Arrow’s &lt;a href=&quot;https://arrow-kt.io/docs/arrow/core/try/&quot;&gt;Try&lt;/a&gt; has matured but, as I read it, is now being deprecated as their approved way of representing errors. The Kotlin Standard Library has gained a &lt;a href=&quot;https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html&quot;&gt;Result&lt;/a&gt; type that we &lt;a href=&quot;https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md#limitations&quot;&gt;aren’t allowed to return&lt;/a&gt;, and &lt;a href=&quot;https://github.com/npryce/result4k&quot;&gt;Result4k&lt;/a&gt; became useable by dint of renaming its types &lt;code&gt;Success&lt;/code&gt; and &lt;code&gt;Failure&lt;/code&gt; rather than &lt;code&gt;Ok&lt;/code&gt; and &lt;code&gt;Err&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So if you want to pick a functional error handling type for your project, not much has become clearer in 12 months!&lt;/p&gt;

&lt;p&gt;I can however report one experimental result. I migrated a multi-person-month codebase from a result type based on Arrow &lt;a href=&quot;https://arrow-kt.io/docs/arrow/core/either/&quot;&gt;Either&lt;/a&gt; to a hand-rolled algebraic data type&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;sealed class Result&amp;lt;out R&amp;gt;

data class Success&amp;lt;out R&amp;gt;(val value: R) : Result&amp;lt;R&amp;gt;()
data class Failure(val exception: Exception) : Result&amp;lt;Nothing&amp;gt;()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The refactoring took less than a day and introduced no errors (that I found ;-). This is good news, because it is an existence proof that, at least for my style of programming, you could pick one result type for your codebase and change your mind with little pain.&lt;/p&gt;

&lt;p&gt;This of course only applies if you can change the clients of your API. Library writers should probably still just throw exceptions unless they have a compelling reason not to, or else define their own minimal result type.&lt;/p&gt;

&lt;p&gt;Based on talking to Andrey Breslav at KotlinConf I suspect that Jetbrains are just being ultra-cautious, and that restrictions on the use of the standard &lt;code&gt;Result&lt;/code&gt; will be removed as they gain confidence in it. It’s worth noting though that the implementation is an inline class, not an algebraic data type. What this means in practice is that you cannot switch on the type. Instead of writing&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val thang = when (result) {
    is Success -&amp;gt; &quot;win&quot;
    is Failure -&amp;gt; &quot;fail&quot;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;you have to write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val thang = when {
    result.isSuccess -&amp;gt; &quot;win&quot;
    result.isFailure -&amp;gt; &quot;fail&quot;
    else -&amp;gt; error(&quot;Could contracts sort this out?&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is obviously yuk, so if you want to have an easy migration to the standard type when it is allowed as a return type, I would learn to love fold&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val thang = result.fold(
    onSuccess -&amp;gt; { &quot;win&quot; },
    onFailure -&amp;gt; { &quot;fail&quot; }
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which you can use with both an ADT and the standard type, although note that the latter has the &lt;code&gt;onSuccess&lt;/code&gt; parameter first in contrast to most Either-based results, so to future-proof as well as for clarity I would make sure to name both arguments.&lt;/p&gt;

&lt;h2 id=&quot;next-time&quot;&gt;Next Time&lt;/h2&gt;

&lt;p&gt;I hadn’t actually meant for this to be the subject of Part 6, but in the end I thought that a review was appropriate given the amount of time that has passed. This has been a bit off the cuff though, so I’d love to know if you agree or have a different perspective.&lt;/p&gt;

&lt;p&gt;I have been thinking a lot about the broader topic of error handling recently, as &lt;a href=&quot;http://www.natpryce.com/&quot;&gt;Nat Pryce&lt;/a&gt; and I have proposed a session based on our experiences in this area for KotlinConf 2019. With luck the next episode can get around to what I had planned to write about - avoiding errors.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Kotlin Hacks - .printed()</title>
   <link href="http://0.0.0.0:4000/kotlin-hacks-printed.html"/>
   <updated>2019-06-06T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/kotlin-hacks-printed</id>
   <content type="html">&lt;p&gt;Say you have a function&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sum(x: Int, y: Int) = x + y 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and for some reason you suspect that it is going wrong. You’d like to print the return value to the console. So you extract the expression to a variable, print it, and return it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sum(x: Int, y: Int): Int {
    val result =  x + y
    println(result)
    return result
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmmm, for a temporary change, that escalated pretty quickly. We could do better with &lt;a href=&quot;https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/also.html&quot;&gt;also&lt;/a&gt;, which translates a receiver into a lambda parameter&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sum(x: Int, y: Int) = (x + y).also { println(it) } 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This at least doesn’t change the shape of our code and so is easily reversible.&lt;/p&gt;

&lt;p&gt;We can do better though by extracting the also invocation into a function - &lt;code&gt;printed&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; T.printed(): T = this.also { println(it) }

fun sum(x: Int, y: Int) = (x + y).printed() 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you want some choices about where and how the value is printed then default arguments ride to the rescue&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; T.printed(format: String = &quot;%s\n&quot;, stream: PrintStream = System.out): T =
    this.also { stream.format(format, this) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which can be used as previously with no arguments, or, for example&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sum(x: Int, y: Int) = (x + y).printed(&quot;sum is %s\n&quot;, System.err) 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Use of &lt;code&gt;printed&lt;/code&gt; isn’t restricted to return values&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sum(x: Int, y: Int) = x.printed() + y.printed() 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and this use in the middle of expressions can be really useful to avoid having to tear apart chains of calls&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun foo(x: Int, y: Int) = bar(x).baz(y) 

fun foo(x: Int, y: Int) = bar(x).printed().baz(y) 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can pull a similar stunt for printing collections on multiple lines&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T: Iterable&amp;lt;*&amp;gt;&amp;gt; T.printedAsList(format: String = &quot;%s\n&quot;, stream: PrintStream = System.out): T =
    this.also { it.map { item -&amp;gt; item.printed(format, stream) } }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and even, although this is quite fragile, have overloads for &lt;code&gt;InputStream&lt;/code&gt;s and &lt;code&gt;Reader&lt;/code&gt;s&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun InputStream.printed(stream: PrintStream = System.out, charset: Charset = Charsets.UTF_8) =
    bufferedReader(charset).printed(stream)

fun Reader.printed(stream: PrintStream = System.out, charset: Charset = Charsets.UTF_8) =
    readText().printed(stream = stream).byteInputStream(charset)

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I hope that you find these useful - I keep them in a file called &lt;code&gt;debugging.kt&lt;/code&gt; and just copy it into every project. If you have any improvements please let me know in the comments below.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 7</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-7.html"/>
   <updated>2019-06-03T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-7</id>
   <content type="html">&lt;p&gt;This is the final part in a series documenting my experiences learning Android development in Kotlin. The code is available to follow along on &lt;a href=&quot;https://github.com/dmcg/PressToTest&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-1.html&quot;&gt;Part 1&lt;/a&gt; I got a simple UI toy up and running, with tests running via &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; in an emulator.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-2.html&quot;&gt;Part 2&lt;/a&gt; I used &lt;a href=&quot;http://robolectric.org/&quot;&gt;Roboletric&lt;/a&gt; to get (a lightly refactored version of) the same tests running in a local JVM rather than the emulator.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-3.html&quot;&gt;Part 3&lt;/a&gt; was spent working out how to wait for a condition (the snack bar disappearing) on both the emulator and Robolectric tests.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-4.html&quot;&gt;Part 4&lt;/a&gt; and &lt;a href=&quot;press-to-test-part-5.html&quot;&gt;Part 5&lt;/a&gt; I added unit tests that can run without the ten-second Robolectric tax by introducing something that I &lt;em&gt;think&lt;/em&gt; is a ViewModel, but doesn’t look anything like Google’s examples.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-6.html&quot;&gt;Part 6&lt;/a&gt; was spent using &lt;a href=&quot;https://developer.android.com/topic/libraries/data-binding&quot;&gt;Data Binding&lt;/a&gt; to wire up the ViewModel in a way that I think is probably more like the &lt;a href=&quot;https://developer.android.com/topic/libraries/architecture&quot;&gt;Android Architecture Components&lt;/a&gt; have in mind.&lt;/p&gt;

&lt;p&gt;This final episode tries to draw some conclusions from the journey to date.&lt;/p&gt;

&lt;h2 id=&quot;but-first-some-swing&quot;&gt;But First, Some Swing&lt;/h2&gt;

&lt;p&gt;Between 1998 and 2010 most of my development work was in &lt;a href=&quot;https://en.wikipedia.org/wiki/Swing_(Java)&quot;&gt;Swing&lt;/a&gt;, a now deprecated though still working cross-platform GUI toolkit.&lt;/p&gt;

&lt;p&gt;I thought that it would be instructive to reimplement PressToTest, test-first, in Swing. I won’t take you through the process, but here is the result.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    var boomCount = 0
    val button = JButton().apply {
        PressToTestModel(this, &quot;Press to Test&quot;, &quot;Release to Detonate&quot;) {
            boomCount++
        }
    }

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, button.text)

        button.dispatchEvent(mouseEvent(MOUSE_PRESSED))
        assertEquals(&quot;Release to Detonate&quot;, button.text)

        button.dispatchEvent(mouseEvent(MOUSE_RELEASED))
        assertEquals(&quot;Press to Test&quot;, button.text)
    }

    @Test
    fun `clicking button sets off the explosion`() {
        assertEquals(0, boomCount)

        button.doClick()
        assertEquals(1, boomCount)

        button.doClick()
        assertEquals(2, boomCount)
    }

    private fun mouseEvent(eventType: Int) = MouseEvent(button, eventType, currentTimeMillis(), 0, 0, 0, 0, false)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestModel(
    private val button: JButton,
    private val defaultMessage: String,
    private val pressedMessage: String,
    private val action: () -&amp;gt; Unit
) {

    init {
        button.text = defaultMessage
        button.addActionListener {  action() }
        button.addMouseListener(object : MouseAdapter() {
            override fun mousePressed(e: MouseEvent) {
                button.text = pressedMessage
            }
            override fun mouseReleased(e: MouseEvent) {
                button.text = defaultMessage
            }
        })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun main() {
    val button = JButton().apply {
        PressToTestModel(this, &quot;Press to Test&quot;, &quot;Release to Detonate&quot;) {
            JOptionPane.showMessageDialog(this, &quot;Boom&quot;)
        }
    }

    JFrame(&quot;Press to Test&quot;).apply {
        contentPane.add(button)
        pack()
        setLocationRelativeTo(null)
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That’s it. No XML, no 20,000 line Java source files generated from that XML, no Java source files generated to implement the data binding from that XML, no Gradle plugins to make sure that all that generation is done, and no IDE plugins to make sure that when I drill into the generated code I end up looking at the XML that it came from.&lt;/p&gt;

&lt;p&gt;If I wanted a more acceptance-level test I could invoke &lt;code&gt;main&lt;/code&gt; from a JUnit test, find the button by ID or text and manipulate it using a &lt;a href=&quot;https://docs.oracle.com/javase/8/docs/api/java/awt/Robot.html&quot;&gt;Robot&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now this is a disingenuous comparison. Swing had the luxury (and curse) of rendering the UI itself, so that almost everything is pure Java. Android also has a more complicated app lifecycle model, so that managing consistency of state between a long-running application and a short-running activity is (necessarily?) complicated. And we shouldn’t forget that Swing assumes that it is running on a desktop-class OS, where Android is mobile - although the cheapest current Android phones are a class above the desktop that Swing was targeting in 1998.&lt;/p&gt;

&lt;h2 id=&quot;could-do-better&quot;&gt;Could Do Better&lt;/h2&gt;

&lt;p&gt;What I have discovered in this journey is that, even with its constraints, Android doesn’t really seem to try hard enough to make unit testing its UIs easy.&lt;/p&gt;

&lt;p&gt;A GUI decoupling pattern like &lt;a href=&quot;https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel&quot;&gt;MVVM&lt;/a&gt; should allow us to test our view logic without having real UI components, by working in terms of interfaces and data-binding. Our Android &lt;code&gt;ViewModel&lt;/code&gt; is able to implement the &lt;code&gt;OnTouchListener&lt;/code&gt; and &lt;code&gt;OnClickListener&lt;/code&gt; interfaces to be notified of changes, and bind its &lt;code&gt;buttonText&lt;/code&gt; &lt;code&gt;LiveModel&lt;/code&gt; to the button’s text, all without being aware of &lt;code&gt;Button&lt;/code&gt;. In this way we can test the &lt;code&gt;ViewModel&lt;/code&gt; without having to create an actual &lt;code&gt;Button&lt;/code&gt;, which we can only do on an ‘actual’ device. All the pieces to implement this pattern are in place.&lt;/p&gt;

&lt;p&gt;As I found though, if you then try to test this setup, you find that you cannot create the events that are propagated through the interfaces - in particular &lt;code&gt;MotionEvent&lt;/code&gt; - in your tests. Introducing the Robolectric fake Android API can solve this problem, but only at the expense of horrible test startup times.&lt;/p&gt;

&lt;p&gt;There is another problem with Robolectric, which is that in order to use it, you have to run your tests with the &lt;code&gt;RobolectricTestRunner&lt;/code&gt; (maybe not directly, the &lt;code&gt;AndroidJUnit4&lt;/code&gt; test runner delegates to Robolectric for unit tests). Each test can only have one runner, which prevents the use of other &lt;a href=&quot;https://github.com/dmcg/minutest&quot;&gt;interesting testing techniques&lt;/a&gt;. The &lt;code&gt;RobolectricTestRunner&lt;/code&gt; is also intimately tied to JUnit 4, and Google are &lt;a href=&quot;https://github.com/robolectric/robolectric/issues/3477&quot;&gt;in no hurry&lt;/a&gt; to fix that. To be fair, they are caught a bit between a rock and a hard place - they &lt;em&gt;could&lt;/em&gt; fix the single test runner issue by reimplementing Robolectric support as a &lt;a href=&quot;https://github.com/junit-team/junit4/wiki/rules&quot;&gt;JUnit Rule&lt;/a&gt;, but these aren’t well supported by JUnit 5. Sigh.&lt;/p&gt;

&lt;p&gt;Given the difficulties that I found using Robolectric (slow startup, having to poke it to advance time, having to kick it to acknowledge the activity lifecycle, cannot integrate with other testrunners) I’m really not sure that it is worth the effort over a combination of the more completely decoupled unit tests that I ended up writing and running code on the simulator. Except that the simulator would be a challenge to run as part of a server-hosted continuous integration setup, which is probably the reason that people persist with Robolectric.&lt;/p&gt;

&lt;p&gt;On the plus side, one of the reasons that Robolectric seems a marginal gain is that running acceptances tests against a real app running in a simulator proves to be so simple and reliable. So kudos to Google for Espresso and the tooling around it.&lt;/p&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;I think that this toy example has run its course. Thanks to all those who provided feedback.&lt;/p&gt;

&lt;p&gt;What about you? Do you agree with my conclusions, or do you have a different experience? Maybe there are tricks that I have missed? If so, please do let me know, either in the comments below, via &lt;a href=&quot;https://twitter.com/duncanmcg&quot;&gt;Twitter&lt;/a&gt; or &lt;a href=&quot;http://oneeyedmen.com/mailto:duncan@oneeyedmen.com&quot;&gt;email&lt;/a&gt;. Thank you.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 6</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-6.html"/>
   <updated>2019-05-30T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-6</id>
   <content type="html">&lt;p&gt;This is Part 6 in a series documenting my experiences learning Android development in Kotlin. The code is available to follow along on &lt;a href=&quot;https://github.com/dmcg/PressToTest&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-1.html&quot;&gt;Part 1&lt;/a&gt; I got a simple UI toy up and running, with tests running via &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; in an emulator.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-2.html&quot;&gt;Part 2&lt;/a&gt; I used &lt;a href=&quot;http://robolectric.org/&quot;&gt;Roboletric&lt;/a&gt; to get (a lightly refactored version of) the same tests running in a local JVM rather than the emulator.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-3.html&quot;&gt;Part 3&lt;/a&gt; was spent working out how to wait for a condition (the snack bar disappearing) on both the emulator and Robolectric tests.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-4.html&quot;&gt;Part 4&lt;/a&gt; and &lt;a href=&quot;press-to-test-part-5.html&quot;&gt;Part 5&lt;/a&gt; I added unit tests that can run without the ten-second Robolectric tax by introducing something that I &lt;em&gt;think&lt;/em&gt; is a ViewModel, but doesn’t look anything like Google’s examples.&lt;/p&gt;

&lt;p&gt;In those last two episodes I spent my time avoiding the &lt;a href=&quot;https://developer.android.com/topic/libraries/architecture&quot;&gt;Android Architecture Components&lt;/a&gt;, which include a ViewModel and LiveData and other things that are designed to help in this sort of situation. This was because every time I read the documentation I wanted to give up programming and live on a remote island with only 1950’s technology - maybe the Isle of Wight.&lt;/p&gt;

&lt;p&gt;The time has now come to bite the bullet, because at some point I have to find some work, and I don’t suppose most potential gigs will be hand-rolling their own ViewModels. So today I shall mostly be wearing Architecture Components.&lt;/p&gt;

&lt;h2 id=&quot;the-warmup&quot;&gt;The Warmup&lt;/h2&gt;

&lt;p&gt;I start by working my way through the &lt;a href=&quot;https://codelabs.developers.google.com/codelabs/android-databinding&quot;&gt;Data Binding Codelab&lt;/a&gt;. It all kind of makes sense, although for my taste too many important details are buried in XML files, and in code embedded in XML attributes in particular. One thing that I do become aware of is that lifecyle is important - as activities can be restarted we want continuity, but not at the expense of memory leaks.&lt;/p&gt;

&lt;p&gt;OK, I can’t put it off any longer.&lt;/p&gt;

&lt;h2 id=&quot;migration&quot;&gt;Migration&lt;/h2&gt;

&lt;p&gt;Migration of PressToTest starts in Gradle&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-groovy&quot;&gt;android {
    ...
    dataBinding {
        enabled true
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then I need to add a &lt;code&gt;data&lt;/code&gt; element to &lt;code&gt;activity_main.xml&lt;/code&gt;. Unfortunately I seem to need to add it into a root element that doesn’t exist in my (Android Studio generated) layout file. Ho hum. I add the missing root element and the data element and &lt;a href=&quot;https://github.com/dmcg/PressToTest/commit/543d4a7cdec6b1ee73e8c6696579ba26f0aad22d&quot;&gt;this version&lt;/a&gt; still builds and runs.&lt;/p&gt;

&lt;p&gt;Now, to cut a long story short, there is an unedifying hour of faff when I discover that my project (created only a week ago using Android Studio’s new project command) is using APIs in &lt;code&gt;com.android.support&lt;/code&gt; and the data binding examples are all using APIs from &lt;code&gt;androidx&lt;/code&gt;. I try to fix Gradle library references by hand and end up in all sorts of trouble trying to find compatible versions of things. I go to bed with a messed up build.&lt;/p&gt;

&lt;p&gt;With early morning clarity I think to Google for “androidx migration”. The results point me to an Android Studio command - &lt;code&gt;Migrate to AndroidX&lt;/code&gt; - and then warn about all the ways that it will fail to go a good job. I’ve nothing to loose, so I rollback, &lt;a href=&quot;https://github.com/dmcg/PressToTest/commit/7d6b455484914872246d7d88b18664964b1d673d&quot;&gt;invoke the command&lt;/a&gt;, and everything builds and runs just as before!&lt;/p&gt;

&lt;p&gt;[Edit - looks like I spoke too soon. It did run, but later on the tests failed to build and &lt;a href=&quot;https://github.com/dmcg/PressToTest/commit/5d5302a95132bf3b8f4a3de85850fd1393dfd7df&quot;&gt;had to be fixed&lt;/a&gt;.]&lt;/p&gt;

&lt;p&gt;Making the button label in &lt;code&gt;ViewModel&lt;/code&gt; a &lt;code&gt;LiveData&lt;/code&gt; seems like the next logical step.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    private val defaultText: String,
    private val pressedText: String,
    private val onButtonTextChanged: (String) -&amp;gt; Unit,
    private var goBoom: () -&amp;gt; Unit
) {
//    private var buttonText: String by Delegates.observable(defaultText) { _, _, newValue -&amp;gt;
//        onButtonTextChanged(newValue)
//    }

    var buttonText = MutableLiveData&amp;lt;String&amp;gt;(defaultText)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I find that &lt;code&gt;MutableLiveData&lt;/code&gt; doesn’t have a constructor taking the default value; except it does in the code lab that I’ve just completed. I sigh, look for the differences between the codelab build and my own and add &lt;code&gt;implementation &quot;androidx.lifecycle:lifecycle-extensions:2.1.0-alpha04&quot;&lt;/code&gt; which seems to do the trick.&lt;/p&gt;

&lt;p&gt;Apart from that, the binding of the button text to a &lt;code&gt;LiveData&lt;/code&gt; is remarkably painless. Add a data section to the layout and reference our &lt;code&gt;ViewModel&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;    &amp;lt;data&amp;gt;
        &amp;lt;variable
            name=&quot;viewmodel&quot;
            type=&quot;com.oneeyedmen.presstotest.ViewModel&quot;/&amp;gt;
    &amp;lt;/data&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Tell the layout that the button’s text should use &lt;code&gt;viewmodel.buttonText&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;    &amp;lt;Button
            android:text=&quot;@{viewmodel.buttonText}&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Have the &lt;code&gt;ViewModel&lt;/code&gt; update the &lt;code&gt;MutableLiveData&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    // ...
) {

    var buttonText = MutableLiveData&amp;lt;String&amp;gt;(defaultText)

    @VisibleForTesting
    internal fun onTouchAction(actionCode:Int) {
        when (actionCode) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText.value = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText.value = defaultText
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and use &lt;code&gt;DataBindingUtil.setContentView&lt;/code&gt; rather then &lt;code&gt;AppCompatActivity.setContentView&lt;/code&gt; to wire up the databinding in &lt;code&gt;MainActivity&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        DataBindingUtil.setContentView&amp;lt;ActivityMainBinding&amp;gt;(this, R.layout.activity_main).let {
            it.lifecycleOwner = this
            it.viewmodel = ViewModel(
                button = button,
                defaultText = getString(R.string.default_button_label),
                pressedText = getString(R.string.pressed_button_label),
                goBoom = this::boom
            )
        }
    }

    private fun boom() {
        Snackbar.make(button, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
            .setAction(&quot;Action&quot;, null).show()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Awesomely this runs, and works, and passes the &lt;code&gt;InstrumentedAcceptanceTests&lt;/code&gt;. Less awesomely, Android Studio lets me do all those things without warning me that my unit tests no longer compile. No matter, the test can be simpler now because it can read directly from the &lt;code&gt;buttonText&lt;/code&gt; &lt;code&gt;LiveModel&lt;/code&gt; safe in the knowledge that data binding has its back.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {
    // ...

    val viewModel = ViewModel(
        defaultText = &quot;Press to Test&quot;,
        pressedText = &quot;Release to Detonate&quot;,
        goBoom = { boomCount++ }
    )

    private val buttonText get() = viewModel.buttonText.value

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_DOWN)
        assertEquals(&quot;Release to Detonate&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_UP)
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run that and - oh no not again &lt;code&gt;java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.&lt;/code&gt; The top hit on Google provides the answer - add an &lt;code&gt;InstantTaskExecutorRule&lt;/code&gt;, as had been previously &lt;a href=&quot;https://www.reddit.com/r/Kotlin/comments/buqqt1/press_to_test_parts_4_and_5_cover_unit_testing/epg3cw3&quot;&gt;predicted on Reddit&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now I run the last remaining test - the Robolectric &lt;code&gt;InternalAcceptanceTest&lt;/code&gt;, which fails - apparently Espresso says that the button’s label hasn’t changed after the touch event. I try adding the &lt;code&gt;InstantExecutorRule&lt;/code&gt; - no dice. I try waiting for the label change - no dice. I break out the debugger and find that when the ‘LiveData’ changes it sees its observer as inactive, so does nothing.&lt;/p&gt;

&lt;p&gt;I return to Google, ending up searching for ‘“livedata” “robolectric” “inactive”’, and the top hit of &lt;a href=&quot;https://github.com/robolectric/robolectric/issues/3234&quot;&gt;LiveData seems to not notify observers&lt;/a&gt; looks promising. It’s an unfixed bug in Robolectric, with a &lt;a href=&quot;https://github.com/robolectric/robolectric/issues/3234#issuecomment-319514954&quot;&gt;workaround&lt;/a&gt; of &lt;code&gt;activityController.get().getLifecycle().handleLifecycleEvent(Lifecycle.Event.ON_START)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Unfortunately there’s no clue as to where to put this code, but I figure that before every test would be a good bet, so I add an &lt;code&gt;@Before&lt;/code&gt; to the &lt;code&gt;InternalAcceptanceTests&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class InternalAcceptanceTests : AcceptanceTests(robolectricWaiter) {
    @Before fun hack() {
        activityController.get().getLifecycle().handleLifecycleEvent(Lifecycle.Event.ON_START)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which of course doesn’t compile, and I have no idea what the &lt;code&gt;activityController&lt;/code&gt; is. I find that &lt;a href=&quot;https://developer.android.com/reference/android/arch/lifecycle/LifecycleRegistry.html#handleLifecycleEvent(android.arch.lifecycle.Lifecycle.Event)&quot;&gt;handleLifecycleEvent&lt;/a&gt; is a method on &lt;code&gt;LifecyleRegistry&lt;/code&gt;, and &lt;code&gt;LifeCycleRegistry&lt;/code&gt; is a subtype of &lt;code&gt;LifeCycle&lt;/code&gt;, so in the end just guess and try&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class InternalAcceptanceTests : AcceptanceTests(robolectricWaiter) {
    @Before fun hack() {
        (activityRule.activity.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_START)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which works, at least for this test! Quick, check it in.&lt;/p&gt;

&lt;h2 id=&quot;events-dear-boy&quot;&gt;Events Dear Boy&lt;/h2&gt;

&lt;p&gt;Now we have used Data Binding to observe &lt;code&gt;ViewModel.buttonText&lt;/code&gt; and update the, erm, button text, but we still have manual wiring of &lt;code&gt;ViewModel&lt;/code&gt; to listen to the &lt;code&gt;Button&lt;/code&gt;’s events.&lt;/p&gt;

&lt;p&gt;Now it &lt;a href=&quot;https://stackoverflow.com/a/49785261/97777&quot;&gt;looks like&lt;/a&gt; I can associate the button’s &lt;code&gt;OnTouchListener&lt;/code&gt; with the &lt;code&gt;ViewModel&lt;/code&gt; if I revert to exporting a listener property, viz&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    //...
) {
    val onTouchListener = OnTouchListener { _, event -&amp;gt;
        onTouchAction(event.action)
        false
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and do the binding in the XML&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;    &amp;lt;Button
        android:id=&quot;@+id/button&quot;
        android:text=&quot;@{viewmodel.buttonText}&quot;
        app:onTouchListener=&quot;@{viewmodel.onTouchListener}&quot;
        ...
    /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That passes the tests, even when I remove the code to add the &lt;code&gt;OnTouchListener&lt;/code&gt; to the &lt;code&gt;Button&lt;/code&gt; in the &lt;code&gt;ViewModel&lt;/code&gt; constructor. So I do the same with the &lt;code&gt;onClickListener&lt;/code&gt; so that in the end the &lt;code&gt;ViewModel&lt;/code&gt; secondary constructor disappears and we are left with&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    @get:Rule
    val rule = InstantTaskExecutorRule()

    private var boomCount = 0

    val viewModel = ViewModel(
        defaultText = &quot;Press to Test&quot;,
        pressedText = &quot;Release to Detonate&quot;,
        goBoom = { boomCount++ }
    )

    private val buttonText get() = viewModel.buttonText.value

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_DOWN)
        assertEquals(&quot;Release to Detonate&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_UP)
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }

    @Test
    fun `clicking button sets off the explosion`() {
        assertEquals(0, boomCount)

        viewModel.onClick()
        assertEquals(1, boomCount)

        viewModel.onClick()
        assertEquals(2, boomCount)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    private val defaultText: String,
    private val pressedText: String,
    private var goBoom: () -&amp;gt; Unit
) {
    var buttonText = MutableLiveData&amp;lt;String&amp;gt;(defaultText)

    val onTouchListener = OnTouchListener { _, event -&amp;gt;
        onTouchAction(event.action)
        false
    }

    val onClickListener = OnClickListener { onClick() }

    @VisibleForTesting
    internal fun onTouchAction(actionCode: Int) {
        when (actionCode) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText.value = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText.value = defaultText
        }
    }

    @VisibleForTesting
    internal fun onClick() {
        goBoom()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        DataBindingUtil.setContentView&amp;lt;ActivityMainBinding&amp;gt;(this, R.layout.activity_main).let {
            it.lifecycleOwner = this
            it.viewmodel = ViewModel(
                defaultText = getString(R.string.default_button_label),
                pressedText = getString(R.string.pressed_button_label),
                goBoom = this::boom
            )
        }
    }

    private fun boom() {
        Snackbar.make(button, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
            .setAction(&quot;Action&quot;, null).show()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&amp;gt;
&amp;lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&amp;gt;

    &amp;lt;data&amp;gt;
        &amp;lt;variable
            name=&quot;viewmodel&quot;
            type=&quot;com.oneeyedmen.presstotest.ViewModel&quot;/&amp;gt;
    &amp;lt;/data&amp;gt;
    &amp;lt;androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;com.oneeyedmen.presstotest.MainActivity&quot;&amp;gt;

        &amp;lt;Button
            android:id=&quot;@+id/button&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:text=&quot;@{viewmodel.buttonText}&quot;
            android:onClickListener=&quot;@{viewmodel.onClickListener}&quot;
            app:onTouchListener=&quot;@{viewmodel.onTouchListener}&quot;
            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
            app:layout_constraintEnd_toEndOf=&quot;parent&quot;
            app:layout_constraintStart_toStartOf=&quot;parent&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&amp;gt;

    &amp;lt;/androidx.constraintlayout.widget.ConstraintLayout&amp;gt;
&amp;lt;/layout&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;punt&quot;&gt;Punt&lt;/h2&gt;

&lt;p&gt;That just leaves the &lt;code&gt;goBoom&lt;/code&gt; action not translated to the new newness. Googling for “livedata snackbar” gives a lot of hits about &lt;code&gt;SingleLiveEvent&lt;/code&gt;, but this isn’t part of the standard API and there seem to be competing implementations. I’m reasonably convinced that I don’t have to care about lifecycles with the current &lt;code&gt;goBoom: () -&amp;gt; Unit&lt;/code&gt; implementation, and it has been a tiring day. so I punt and leave the snackbar invocation as it is. Philosophically I think that there is a difference between the databinding used for the label and the boom - the former is just data synchronisation whereas the latter is an effect (both in the audiovisual and functional programming sense) - so I’m happy to leave them looking different.&lt;/p&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;Mid way through this post I would have bet that I would be rejecting the data binding approach now and rolling back the code. Actually, when I &lt;a href=&quot;https://github.com/dmcg/PressToTest/compare/38517c913eb68f5a4b1c2fc7d266a0cfbf9f5bab..bdf11ff75c12a598cf4c517967b6ec75aa05cd39&quot;&gt;compare the two solutions&lt;/a&gt; I think that the data-binding wins out. The details hidden in the XML aren’t too bad and &lt;code&gt;ViewModel&lt;/code&gt; is simplified by the removal of that ugly constructor. It’s a shame that it requires code-generation behind the scenes to work though, and that I had to bodge the Robolectric Espresso test to get it working.&lt;/p&gt;

&lt;p&gt;I think that I have one more installment in me. I plan to return to my &lt;a href=&quot;https://docs.oracle.com/javase/7/docs/api/javax/swing/package-summary.html&quot;&gt;happy place&lt;/a&gt; and reimplement this example to give some perspective on the Android solution.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 5</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-5.html"/>
   <updated>2019-05-29T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-5</id>
   <content type="html">&lt;p&gt;This is Part 5 in a series documenting my experiences learning Android development in Kotlin. The code is available to follow along on &lt;a href=&quot;https://github.com/dmcg/PressToTest&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-1.html&quot;&gt;Part 1&lt;/a&gt; I got a simple UI toy up and running, with tests running via &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; in an emulator.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-2.html&quot;&gt;Part 2&lt;/a&gt; I used &lt;a href=&quot;http://robolectric.org/&quot;&gt;Roboletric&lt;/a&gt; to get (a lightly refactored version of) the same tests running in a local JVM rather than the emulator.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-3.html&quot;&gt;Part 3&lt;/a&gt; was spent working out how to wait for a condition (the snack bar disappearing) on both the emulator and Robolectric tests.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-4.html&quot;&gt;Part 4&lt;/a&gt; I spent a whole day trying to write a single unit test that was sufficiently decoupled from the Android runtime to run without Robolectric.&lt;/p&gt;

&lt;p&gt;This time I’ve learned not to try to predict what will happen! But my aim is to add unit tests for the ‘Boom’ message and to try to simplify the tests, perhaps by making use of supplied support classes.&lt;/p&gt;

&lt;h2 id=&quot;the-code-so-far&quot;&gt;The Code So Far&lt;/h2&gt;

&lt;p&gt;Here’s the code to date - if you haven’t already you could read &lt;a href=&quot;press-to-test-part-4.html&quot;&gt;Part 4&lt;/a&gt; to see how it got that way.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    var buttonText = &quot;DEFAULT&quot;
    val viewModel = ViewModel { buttonText = it }

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_DOWN)
        assertEquals(&quot;Release to Detonate&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_UP)
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }
}

class ViewModel(
    private val onButtonTextChanged: (String) -&amp;gt; Unit
) {

    private val defaultText = &quot;Press to Test&quot;
    private val pressedText = &quot;Release to Detonate&quot;

    var buttonText: String by Delegates.observable(defaultText) { _, _, newValue -&amp;gt;
        onButtonTextChanged(newValue)
    }

    init {
        // required to sync the view on creation
        buttonText = defaultText
    }

    fun onTouchAction(actionCode:Int) {
        when (actionCode) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText = defaultText
        }
    }

    val onTouchListener = View.OnTouchListener { v, event -&amp;gt;
        onTouchAction(event.actionMasked)
        false
    }
}

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewModel = ViewModel(onButtonTextChanged = button::setText)
        button.setOnTouchListener(viewModel.onTouchListener)

        button.setOnClickListener { view -&amp;gt;
            Snackbar.make(view, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
                .setAction(&quot;Action&quot;, null).show()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;data-binding-or-more-tests&quot;&gt;Data Binding or More Tests?&lt;/h2&gt;

&lt;p&gt;After completing this I spend a couple of hours overall reading up on &lt;a href=&quot;https://developer.android.com/topic/libraries/data-binding/index.html&quot;&gt;Data Binding&lt;/a&gt;. It looks like I’ll have to modify quite a bit of the app to use it, and probably work my way through &lt;a href=&quot;https://codelabs.developers.google.com/codelabs/android-databinding&quot;&gt;a codelab&lt;/a&gt; in order to understand what the documentation is talking about. I decide to press on without it for now, if only because working my way through documentation doesn’t provide blog content.&lt;/p&gt;

&lt;h2 id=&quot;so-one-more-test&quot;&gt;So, One More Test&lt;/h2&gt;

&lt;p&gt;The unit test that we are missing is that a snackbar should show “Boom” when the button is clicked. Given all the fun we had trying to test with a &lt;code&gt;Button&lt;/code&gt; I work on the principle that we should avoid any direct reference to snackbars in the &lt;code&gt;ViewModel&lt;/code&gt; and its tests. So I pull the same stunt as before - hide the code-to-make-the-boom behind a function passed into the &lt;code&gt;ViewModel&lt;/code&gt;’s constructor.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    var buttonText = &quot;DEFAULT&quot;
    var boomCount = 0
    val viewModel = ViewModel(
        onButtonTextChanged = { buttonText = it },
        boom = { boomCount++ }
    )

    @Test
    fun `clicking button sets off the explosion`() {
        assertEquals(0, boomCount)

        viewModel.onClick()
        assertEquals(1, boomCount)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;expose a couple of methods on the &lt;code&gt;ViewModel&lt;/code&gt;, one we can call from our tests as it doesn’t need an event (which we can’t create in unit tests), and one that gives access to an event listener&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    private val onButtonTextChanged: (String) -&amp;gt; Unit,
    private var goBoom: () -&amp;gt; Unit
) {

    fun onClick() {
        goBoom()
    }

    val onClickListener = View.OnClickListener { onClick() }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then install into our activity&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewModel = ViewModel(
            onButtonTextChanged = button::setText,
            goBoom = this::boom)
        button.setOnTouchListener(viewModel.onTouchListener)
        button.setOnClickListener(viewModel.onClickListener)
    }

    private fun boom() {
        Snackbar.make(button, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
            .setAction(&quot;Action&quot;, null).show()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that I know not to drive down closed roads, this is a quick and easy, runs as a unit test in milliseconds, and passes our acceptance tests. Woohoo!&lt;/p&gt;

&lt;h2 id=&quot;review&quot;&gt;Review&lt;/h2&gt;

&lt;p&gt;I have a bit of a tidy up, moving installation of &lt;code&gt;ViewModel&lt;/code&gt; with &lt;code&gt;Button&lt;/code&gt; to a &lt;code&gt;ViewModel&lt;/code&gt; constructor and then review the code.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    var buttonText = &quot;DEFAULT&quot;
    var boomCount = 0

    val viewModel = ViewModel(
        defaultText = &quot;Press to Test&quot;,
        pressedText = &quot;Release to Detonate&quot;,
        onButtonTextChanged = { buttonText = it },
        goBoom = { boomCount++ }
    )

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_DOWN)
        assertEquals(&quot;Release to Detonate&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_UP)
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }

    @Test
    fun `clicking button sets off the explosion`() {
        assertEquals(0, boomCount)

        viewModel.onClick()
        assertEquals(1, boomCount)

        viewModel.onClick()
        assertEquals(2, boomCount)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    private val defaultText: String,
    private val pressedText: String,
    private val onButtonTextChanged: (String) -&amp;gt; Unit,
    private var goBoom: () -&amp;gt; Unit
) {
    private var buttonText: String by Delegates.observable(defaultText) { _, _, newValue -&amp;gt;
        onButtonTextChanged(newValue)
    }

    constructor(
        button: Button,
        defaultText: String,
        pressedText: String,
        goBoom: () -&amp;gt; Unit

    ) : this(
        defaultText = defaultText,
        pressedText = pressedText,
        onButtonTextChanged = button::setText,
        goBoom = goBoom
    ) {
        button.setOnTouchListener { _, event -&amp;gt;
            onTouchAction(event.actionMasked)
            false
        }
        button.setOnClickListener {
            onClick()
        }
    }

    init {
        // sync the view on creation
        buttonText = defaultText
    }

    @VisibleForTesting
    internal fun onTouchAction(actionCode:Int) {
        when (actionCode) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText = defaultText
        }
    }

    @VisibleForTesting
    internal fun onClick() {
        goBoom()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ViewModel(
            button = button,
            defaultText = getString(R.string.default_button_label),
            pressedText = getString(R.string.pressed_button_label),
            goBoom = this::boom
        )
    }

    private fun boom() {
        Snackbar.make(button, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
            .setAction(&quot;Action&quot;, null).show()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Actually that isn’t bad. The test is nice and simple and doesn’t rely on any awkward Android classes, &lt;code&gt;MainActivity&lt;/code&gt; is clean, but the relationship between the &lt;code&gt;ViewModel&lt;/code&gt;, the button and the snackbar is nicely explicit. The nastiness is hidden away in in a secondary constructor of &lt;code&gt;ViewModel&lt;/code&gt;, and that looks worse than it is because of Kotlin’s awkward constructor delegation layout and my desire to fit the code on mobile screens.&lt;/p&gt;

&lt;p&gt;Philosophically I like that &lt;code&gt;ViewModel&lt;/code&gt; is now self-contained and asks only to be created with strings, a button and the &lt;code&gt;goBoom&lt;/code&gt; effect. Overall, given the constraints on unit testing, this may be the least-worst solution. Which is least-bad-enough for me.&lt;/p&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;This hasn’t been a full day’s work, but I’m going to stop this post here, as we now have complete acceptance and unit test coverage of the app, albeit hand-crafted. I’d still like to try out that Data Binding though, so I’ll spend the rest of the day working through that codelab so that I can refactor my cobbling &lt;a href=&quot;press-to-test-part-6.html&quot;&gt;tomorrow&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 4</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-4.html"/>
   <updated>2019-05-26T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-4</id>
   <content type="html">&lt;p&gt;This is Part 4 in a series documenting my experiences learning Android development in Kotlin. The code is available to follow along on &lt;a href=&quot;https://github.com/dmcg/PressToTest&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-1.html&quot;&gt;Part 1&lt;/a&gt; I got a simple UI toy up and running, with tests running via &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; in an emulator.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-2.html&quot;&gt;Part 2&lt;/a&gt; I used &lt;a href=&quot;http://robolectric.org/&quot;&gt;Roboletric&lt;/a&gt; to get (a lightly refactored version of) the same tests running in a local JVM rather than the emulator.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-3.html&quot;&gt;Part 3&lt;/a&gt; was spent working out how to wait for a condition (the snack bar disappearing) on both the emulator and Robolectric tests.&lt;/p&gt;

&lt;p&gt;This time we’re going to to capitalise on my new-found Android expertise to test-drive the development of the functionality from scratch. Let’s remind ourselves what it is that we want to verify.&lt;/p&gt;

&lt;h2 id=&quot;the-requirement&quot;&gt;The Requirement&lt;/h2&gt;

&lt;p&gt;The app should show a single button with the label &lt;code&gt;Press to Test&lt;/code&gt;. When you press, but don’t release, the button, its label should change to &lt;code&gt;Release to Detonate&lt;/code&gt;. Releasing the button should result in some audiovisual extravaganza and reset the button for the next victim.&lt;/p&gt;

&lt;p&gt;Unaccountably, a week after first publishing this idea, there is still no app in the Play Store for this.&lt;/p&gt;

&lt;h2 id=&quot;test-first&quot;&gt;Test First&lt;/h2&gt;

&lt;p&gt;This is test-first, so the first thing to do is to create a test and check that we can run it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {
    @Tests
    fun test() {
        fail()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Check ✔︎. Or rather ✘, as the test obligingly fails.&lt;/p&gt;

&lt;p&gt;Now we have to decide which of our two features - the audiovisual extravaganza when you release the button, or the changing button text - to (test and then) implement first. Let’s start with the changing button text, as it comes first chronologically.&lt;/p&gt;

&lt;p&gt;Our test wants to look like this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {
    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)

        touchButton()
        assertEquals(&quot;Release to Detonate&quot;, buttonText)

        untouchButton()
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;where the &lt;code&gt;buttonText&lt;/code&gt; property, &lt;code&gt;touchButton&lt;/code&gt; and &lt;code&gt;untouchButton&lt;/code&gt; are as yet undefined.&lt;/p&gt;

&lt;p&gt;Let’s try the simplest thing that could possibly work.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {
    val button = Button(null)
    val buttonText: String get() = button.text.toString()

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;not-so-fast&quot;&gt;Not So Fast&lt;/h2&gt;

&lt;p&gt;Frankly I expected this to fail when I created the button, but instead I get “java.lang.RuntimeException: Method getText in android.widget.TextView not mocked. See http://g.co/androidstudio/not-mocked for details.” when I access &lt;code&gt;button.text&lt;/code&gt;. I like an error message that I can click, even if is it to a page that “is obsolete and not maintained.” Anyway the gist is that there is only a stub for &lt;code&gt;Button&lt;/code&gt; in the android.jar file that we develop against locally, and all its methods throw.&lt;/p&gt;

&lt;p&gt;That confuses me for a while, as the test next to it in the source tree (&lt;a href=&quot;https://github.com/dmcg/PressToTest/blob/bf9fea38d064f46b255a1eaa4bffd90189b1ef4a/app/src/test/java/com/oneeyedmen/presstotest/InternalAcceptanceTests.kt&quot;&gt;InternalAcceptanceTests&lt;/a&gt;) is working with a button, albeit via Robolectric. Let’s try a variant of that test as a unit test.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {
    
    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)
    
    val buttonText: String get() = activityRule.activity.button.text.toString()
    
    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This throws &lt;code&gt;java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation&lt;/code&gt; in the &lt;code&gt;activityRule&lt;/code&gt; constructor. I ponder, and then realise that &lt;code&gt;InternalAcceptanceTests&lt;/code&gt; are running with a special runner - &lt;code&gt;@RunWith(AndroidJUnit4::class)&lt;/code&gt;. I add that to my current tests&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
class PressToTestTests {
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and this now works, which is to say - I can check the button’s initial text without any exceptions. Success - except that in place of the exceptions there is a ten second wait while my test starts up - the Robolectric tax.&lt;/p&gt;

&lt;p&gt;Now while I only pay that tax once per test run, it’s hardly conducive to a rapid TDD cycle. In fact, ironically, if the emulator is already running I can run my two acceptance tests on it, including installation, in about 5 seconds; whereas the ‘local’ Robolectric tests take at least 10 seconds. As an old Swing developer, used to just firing up my UI in my test VM and throwing events at it, this makes me a bit sad. It looks like if I want fast feedback from my unit tests I’m going to have to avoid real Android views.&lt;/p&gt;

&lt;h2 id=&quot;decoupling&quot;&gt;Decoupling&lt;/h2&gt;

&lt;p&gt;So it’s off to Google again. In some of my previous reading I’ve come across the MVVM &lt;a href=&quot;https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel&quot;&gt;(Model-View-ViewModel)&lt;/a&gt; pattern, and that seems to promise decoupling of my view logic from actual Android view components. But oh my goodness it’s difficult to find a simple example unencumbered by combinations of Architecture Components and Dagger and RxJava and Data Binding and [Click to Add Favourite Framework].&lt;/p&gt;

&lt;p&gt;While I thrash around the Internet trying to work out what a simple solution would look like using none or more of these parts, I can at least sketch out what a viewmodel might look like. It is supposed to sit between the UI and model (the application state), and translate between them - I guess Model-ViewModel-View was a less snappy title. Anyway, as we have no application state, only UI state, this should be quite simple. I recast the tests like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    val viewModel = ViewModel()

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, viewModel.buttonText)

        viewModel.onButtonTouched()
        assertEquals(&quot;Release to Detonate&quot;, viewModel.buttonText)

        viewModel.onButtonUntouched()
        assertEquals(&quot;Press to Test&quot;, viewModel.buttonText)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which lets me write a very simple implementation&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel {

    private val defaultText = &quot;Press to Test&quot;
    private val pressedText = &quot;Release to Detonate&quot;

    var buttonText = defaultText

    fun onButtonTouched() {
        buttonText = pressedText
    }

    fun onButtonUntouched() {
        buttonText = defaultText
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which passes the tests! At least now I have something I can check in to appear to be making progress.&lt;/p&gt;

&lt;p&gt;Having checked it in though, it seems that &lt;code&gt;ViewModel&lt;/code&gt; may not be trying hard enough. We know that the UI does not have separate events for &lt;code&gt;onButtonTouched&lt;/code&gt; and &lt;code&gt;onButtonUntouched&lt;/code&gt;. Instead I choose to let &lt;code&gt;ViewModel&lt;/code&gt; expose an &lt;code&gt;OnTouchListener&lt;/code&gt; which will take the logic that is currently sitting in &lt;a href=&quot;https://github.com/dmcg/PressToTest/blob/4aa0002ce5b6328dbf742494a9ef593ecb93df38/app/src/main/java/com/oneeyedmen/presstotest/MainActivity.kt&quot;&gt;MainActivity.kt&lt;/a&gt; so that we can test that.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel {

    private val defaultText = &quot;Press to Test&quot;
    private val pressedText = &quot;Release to Detonate&quot;

    var buttonText = defaultText

    val onTouchListener = View.OnTouchListener { v, event -&amp;gt;
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText = defaultText
        }
        false
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the tests just simulate the events that will come from a button&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, viewModel.buttonText)

        viewModel.onTouchListener.onTouch(null, motionEventWithAction(MotionEvent.ACTION_DOWN))
        assertEquals(&quot;Release to Detonate&quot;, viewModel.buttonText)

        viewModel.onTouchListener.onTouch(null, motionEventWithAction(MotionEvent.ACTION_UP))
        assertEquals(&quot;Press to Test&quot;, viewModel.buttonText)
    }

    private fun motionEventWithAction(action: Int) = MotionEvent.obtain(0, 0, action, 0.0F, 0.0F, 0)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;except that, sigh, &lt;code&gt;java.lang.RuntimeException: Method obtain in android.view.MotionEvent not mocked. See http://g.co/androidstudio/not-mocked for details.&lt;/code&gt; I’ve been here before and I know that I can solve this problem with Robolectric, but Robolectric is the problem that I’m trying to solve.&lt;/p&gt;

&lt;p&gt;I can’t be the first person to have this problem, so back to Google. I’m definitely not the first person to have this problem! But both cures (Robolectric or PowerMock) are worse than the disease.  The problem is that &lt;code&gt;MotionEvent&lt;/code&gt; is a final class, and evidently intimately intertwingled with the native workings of Android. This is what happens when frameworks are not created hand-in-hand with testing, and is a real shame. This one problem must be wasting hours of developer time and certainly seems to be forcing Google to develop over-complicated workarounds.&lt;/p&gt;

&lt;p&gt;But I need to stop moaning and make some progress - it’s especially hard to justify this testing wheelspin when the app is already working and already has two other sets of tests to prove it! So I move the problem by adding a method &lt;code&gt;onTouchAction&lt;/code&gt; which I can test, and leaving &lt;code&gt;onTouchListener&lt;/code&gt; untested for now. When everything is wired up it will be tested by our acceptance tests in any case.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel {

    private val defaultText = &quot;Press to Test&quot;
    private val pressedText = &quot;Release to Detonate&quot;

    var buttonText = defaultText

    fun onTouchAction(actionCode:Int) {
        when (actionCode) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText = defaultText
        }
    }

    val onTouchListener = View.OnTouchListener { v, event -&amp;gt;
        onTouchAction(event.actionMasked)
        false
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;so now the tests just say&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, viewModel.buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_DOWN)
        assertEquals(&quot;Release to Detonate&quot;, viewModel.buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_UP)
        assertEquals(&quot;Press to Test&quot;, viewModel.buttonText)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and I can wire in my view model (at least for this interaction)&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewModel = ViewModel()

        button.setOnTouchListener(viewModel.onTouchListener)

        button.setOnClickListener { view -&amp;gt;
            Snackbar.make(view, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
                .setAction(&quot;Action&quot;, null).show()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;but-i-digress&quot;&gt;But I Digress&lt;/h2&gt;

&lt;p&gt;You know, I’ve been faffing around for so long now that I actually ran the acceptance tests expecting them to pass. And when they didn’t, I actually ran the app and played with it, thinking that I must have broken the tests rather than that my cunning plan didn’t work. This one of the under-appreciated problems with development - when ‘easy’ things aren’t we still feel the need to make progress, and that need expresses itself in blind optimism, which then results in bugs.&lt;/p&gt;

&lt;p&gt;Finally the evidence of my own clicking and eyes helps me realise that there is no linkage between our &lt;code&gt;ViewModel&lt;/code&gt; and the button text. My previous Googling suggests that there is some data binding library that will help out, but for now I’m going to just hack it in manually.&lt;/p&gt;

&lt;h2 id=&quot;more-noncoupling&quot;&gt;More Noncoupling&lt;/h2&gt;

&lt;p&gt;What we want is to make changes to &lt;code&gt;ViewModel.buttonText&lt;/code&gt; change the text of a button, without having the &lt;code&gt;ViewModel&lt;/code&gt; know about the &lt;code&gt;Button&lt;/code&gt; type, because we can’t create a &lt;code&gt;Button&lt;/code&gt; in our unit tests without booting up Robolectric. If &lt;code&gt;Button&lt;/code&gt; implemented an interface we could use that, but it doesn’t because, well it just doesn’t. The simplest way to implement this decoupling in Kotlin is just to use a function type to hide the actual code being run. So I add a function property to &lt;code&gt;ViewModel&lt;/code&gt;s constructor&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    private val onButtonTextChanged: (String) -&amp;gt; Unit
) {
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and arrange for its implementation to set the text on a button&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewModel = ViewModel(onButtonTextChanged = button::setText)
        button.setOnTouchListener(viewModel.onTouchListener)

        button.setOnClickListener { view -&amp;gt;
            Snackbar.make(view, getString(R.string.explosion), Snackbar.LENGTH_SHORT)
                .setAction(&quot;Action&quot;, null).show()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now the tests can work in terms of the last set text&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PressToTestTests {

    var buttonText = &quot;DEFAULT&quot;
    val viewModel = ViewModel { buttonText = it }

    @Test
    fun `button message changes on pressing`() {
        assertEquals(&quot;Press to Test&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_DOWN)
        assertEquals(&quot;Release to Detonate&quot;, buttonText)

        viewModel.onTouchAction(MotionEvent.ACTION_UP)
        assertEquals(&quot;Press to Test&quot;, buttonText)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and I can implement functionality in &lt;code&gt;ViewModel&lt;/code&gt; with an &lt;code&gt;observable&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ViewModel(
    private val onButtonTextChanged: (String) -&amp;gt; Unit
) {

    private val defaultText = &quot;Press to Test&quot;
    private val pressedText = &quot;Release to Detonate&quot;

    var buttonText: String by Delegates.observable(defaultText) { _, _, newValue -&amp;gt;
        onButtonTextChanged(newValue)
    }

    init {
        // required to sync the view on creation
        buttonText = defaultText
    }

    fun onTouchAction(actionCode:Int) {
        when (actionCode) {
            MotionEvent.ACTION_DOWN -&amp;gt; buttonText = pressedText
            MotionEvent.ACTION_UP -&amp;gt; buttonText = defaultText
        }
    }

    val onTouchListener = View.OnTouchListener { v, event -&amp;gt;
        onTouchAction(event.actionMasked)
        false
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;Finally (7 hours including research and typing this article) I have a true unit test of the first interaction, and the emulator and Robolectric versions of the acceptance tests still pass. I don’t know if what I have counts as MVVM or not, perhaps only MVM, or maybe it’s just a mongrel that will become more refined as I learn more about the official support for testing. At least I now know some of the constraints on Android TDD and may appreciate why some things are as they are.&lt;/p&gt;

&lt;p&gt;Looking back at the code I see a hidden advantage with the &lt;code&gt;ViewModel&lt;/code&gt; - it is now a single point of truth about the default button text, which was previously duplicated between &lt;code&gt;activity_main.xml&lt;/code&gt; and &lt;code&gt;MainActivity.kt&lt;/code&gt;. Generally though things have gotten a bunch more complicated in the name of testability. I’m trusting that in the &lt;a href=&quot;press-to-test-part-5.html&quot;&gt;next episode&lt;/a&gt; we will be able to remove some code as I learn more about Android UI patterns.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 3</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-3.html"/>
   <updated>2019-05-25T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-3</id>
   <content type="html">&lt;p&gt;This is Part 3 in a series documenting my experiences learning Android development in Kotlin. The code is available to follow along on &lt;a href=&quot;https://github.com/dmcg/PressToTest&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-1.html&quot;&gt;Part 1&lt;/a&gt; I got a simple UI toy up and running, with tests running via &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; in an emulator.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-2.html&quot;&gt;Part 2&lt;/a&gt; I used &lt;a href=&quot;http://robolectric.org/&quot;&gt;Roboletric&lt;/a&gt; to get (a lightly refactored version of) the same tests running in a local JVM rather than the emulator.&lt;/p&gt;

&lt;p&gt;In this episode I was &lt;em&gt;going&lt;/em&gt; to look at writing unit tests for the interaction. But there was some feedback on the Kotlin Test Slack channel for Part 1 that said “It’s unfortunate that he kind of blurred the scope of testing, waiting for 3 seconds for the snackbar to disappear.” This criticism is well founded - these randomish waits for things to happen lead to brittle tests where we we can’t trust that failures are actually problems. In Part 2 I compounded the problem in the Robolectric tests, although to be fair I did it in the name of consistency.&lt;/p&gt;

&lt;p&gt;To recap - the issue is that the UI displays a message in a Snackbar, which automatically hides. Instead of waiting for the view to disappear, the tests just sleep for 3 seconds and then check that it has gone. The problem is compounded because on the emulator this happens automatically, whereas in Robolectric we have to idle the shadow looper (whatever that means) to induce it.&lt;/p&gt;

&lt;p&gt;In reality, I think that in the early stages of real project I would be happy enough to leave the wait in the tests and see if there were actually problems. But this whole project is an academic exercise, so I suppose that we should see if we can address this issue, for academic interest.&lt;/p&gt;

&lt;h2 id=&quot;conditionwatcher&quot;&gt;ConditionWatcher&lt;/h2&gt;

&lt;p&gt;In Part 2 I wrote “I’m pretty sure that if I understood what &lt;a href=&quot;https://medium.com/azimolabs/wait-for-it-idlingresource-and-conditionwatcher-602055f32356&quot;&gt;this article&lt;/a&gt; is saying I could find a common solution that does not have a fixed wait time,” so I went off and read &lt;a href=&quot;https://medium.com/azimolabs/wait-for-it-idlingresource-and-conditionwatcher-602055f32356&quot;&gt;that article&lt;/a&gt;. There was a lot of information about how Roboelectric can be told that things are ready for its next interaction, and then code for a &lt;a href=&quot;https://github.com/AzimoLabs/ConditionWatcher&quot;&gt;ConditionWatcher&lt;/a&gt; that basically tests a condition periodically until &lt;a href=&quot;https://github.com/AzimoLabs/ConditionWatcher/blob/1ef420bb0ed496ff0bb6c574b22576ee9fe3998d/conditionwatcher/src/main/java/com/azimolabs/conditionwatcher/ConditionWatcher.java&quot;&gt;either it is met or a timeout occurs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So I pull the ConditionWatcher jar into the project and try it out.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun clicking_button_shows_temporary_BOOM_message() {

        onView(snackBarMatcher).check(doesNotExist())

        onView(buttonMatcher).perform(click())
        onView(snackBarMatcher).check(isDisplayed())

        ConditionWatcher.waitForCondition(object: Instruction() {
            override fun getDescription() = &quot;Snackbar has gone&quot;

            override fun checkCondition(): Boolean = try {
                onView(snackBarMatcher).check(doesNotExist())
                true
            } catch (x: AssertionFailedError) {
                false
            }
        })
        onView(snackBarMatcher).check(doesNotExist())
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see there a nasty interface mismatch between our way of asserting the state of our GUI through Espresso’s &lt;code&gt;onView(matcher).check(viewAssertion)&lt;/code&gt;, which throw &lt;code&gt;AssertionFailedError&lt;/code&gt; if they are not satisfied, and ConditionWatcher’s condition, which returns &lt;code&gt;false&lt;/code&gt; if it is not satisfied. But it’s not a fatal problem, just an irritation, and this code does pass when we run it in the emulator.&lt;/p&gt;

&lt;p&gt;When we run it in a local JVM under Robolectric though it doesn’t pass, because as we previously found out, in order to make the Snackbar hide we have to poke the &lt;code&gt;ShadowLooper&lt;/code&gt;. What we need is something like ConditionWatcher but which does this poking as well as waiting. While we’re at it it would be nice to be able to set different timeouts and poll intervals per call, and to wait for a condition without creating an &lt;code&gt;Instruction&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;So I spend a happy 90 minutes or so writing my own &lt;code&gt;Waiter&lt;/code&gt; class.&lt;/p&gt;

&lt;h2 id=&quot;waiter&quot;&gt;Waiter&lt;/h2&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Waiter(
    val defaultDescription: String = &quot;something&quot;,
    val defaultTimeoutMillis: Long = 60000,
    val defaultPollMillis: Long = 250,
    val twiddler: () -&amp;gt; Unit = {}
) {
    fun waitFor(
        description: String? = null,
        timeoutMillis: Long = -1,
        pollMillis: Long = -1,
        condition: () -&amp;gt; Boolean
    ) {
        val resolvedDescription = description ?: defaultDescription
        val resolvedTimeoutMillis = if (timeoutMillis &amp;gt;= 0 ) timeoutMillis else defaultTimeoutMillis
        val resolvedPollMillis = if (pollMillis &amp;gt;= 0 ) pollMillis else defaultPollMillis

        val endT = System.currentTimeMillis() + resolvedTimeoutMillis
        while (!condition()) {
            if (System.currentTimeMillis() &amp;gt; endT)
                throw TimeoutException(&quot;Timeout waiting for $resolvedDescription after more than $timeoutMillis ms&quot;)
            Thread.sleep(resolvedPollMillis)
            twiddler()
        }
    }

    inline fun &amp;lt;reified T: Throwable&amp;gt; waitForNo(
        description: String? = null,
        timeoutMillis: Long = -1,
        pollMillis: Long = -1,
        crossinline block: () -&amp;gt; Unit
    ) {
        waitFor(description, timeoutMillis, pollMillis) {
            try {
                block()
                true
            } catch (t: Throwable) {
                if (t is T) false else throw t
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and yes, I did write it &lt;a href=&quot;https://github.com/dmcg/PressToTest/blob/4aa0002ce5b6328dbf742494a9ef593ecb93df38/app/src/test/java/com/oneeyedmen/presstotest/WaiterTests.kt&quot;&gt;test first&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To be honest, this is probably overkill, but then it is an academic exercise, so I might be forgiven for stretching my coding legs a little. &lt;code&gt;waitForNo&lt;/code&gt; is a bit suss, but is there to integrate with Espresso thus&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
abstract class AcceptanceTests(private val waiter: Waiter) {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)

    val button = onView(withId(R.id.button))
    val snackBar get() = onView(
        allOf(
            withId(android.support.design.R.id.snackbar_text),
            withText(&quot;BOOM!&quot;)
        )
    )

    @Test
    fun button_message_changes_on_pressing() {
        button.check(matchesIsDisplayed(withText(&quot;PRESS TO TEST&quot;)))

        button.perform(Finger.pressAndHold())
        button.check(matchesIsDisplayed(withText(&quot;RELEASE TO DETONATE&quot;)))

        button.perform(Finger.release())
        button.check(matchesIsDisplayed(withText(&quot;PRESS TO TEST&quot;)))
    }

    @Test
    fun clicking_button_shows_temporary_BOOM_message() {
        snackBar.check(doesNotExist())

        button.perform(click())
        snackBar.check(matchesIsDisplayed())

        waiter.waitForNo&amp;lt;AssertionFailedError&amp;gt;(&quot;Snackbar gone&quot;) {
            snackBar.check(doesNotExist())
        }
    }
}

private fun matchesIsDisplayed(matcher: Matcher&amp;lt;View&amp;gt; = Matchers.any(View::class.java)) = matches(
    allOf(
        ViewMatchers.isDisplayed(),
        matcher
    )
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In &lt;code&gt;androidTest&lt;/code&gt; - we don’t have to pander to Robolectric&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class InstrumentedAcceptanceTests : AcceptanceTests(Waiter())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Whereas in &lt;code&gt;test&lt;/code&gt; we need a waiter that pokes Robolectric every time around its loop.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class InternalAcceptanceTests : AcceptanceTests(robolectricWaiter)

private val robolectricWaiter = Waiter(twiddler = { ShadowLooper.runMainLooperToNextTask() })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There we have it, we can run the same tests on the emulator and locally, and they will both wait for the snackbar to disappear of its own accord, or fail with a &lt;code&gt;TimeoutException&lt;/code&gt; after a minute.&lt;/p&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;Engineering is the balance between getting things right and getting things done. The code is now a more ‘right’ in that it doesn’t just sleep, but I wonder if &lt;code&gt;runMainLooperToNextTask&lt;/code&gt; will result in the Robolectric scheduler getting out of sync with the time that we have waited for the condition to hold. Without an actual problem though - sufficient unto the day is the evil thereof.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-4.html&quot;&gt;Next time&lt;/a&gt; I’ll get back to trying to write some proper unit tests.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 2</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-2.html"/>
   <updated>2019-05-24T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-2</id>
   <content type="html">&lt;p&gt;This is Part 2 in a series documenting my experiences learning Android development in Kotlin.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;press-to-test-part-1.html&quot;&gt;Part 1&lt;/a&gt; I got a simple UI toy up and running, with tests running via &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; in an emulator (and (I assume but haven’t verified) on an actual device).&lt;/p&gt;

&lt;p&gt;I left that episode impressed with how easy it was to run functional test code, but concerned that running all my UI tests this way would be very slow for a real project. Let’s see if we can run the same sort of tests in a local JVM rather than on an Android device.&lt;/p&gt;

&lt;h2 id=&quot;just-too-easy&quot;&gt;Just Too Easy&lt;/h2&gt;

&lt;p&gt;In my Googling around for how to test Android apps &lt;a href=&quot;http://robolectric.org/&quot;&gt;Roboletric&lt;/a&gt; keeps coming up, and I learn that it is a set of fake implementations of Android APIs to let you run Android code in a JVM. Running my Android code in a JVM is exactly what I want to do, so I search for “espresso robolectric testing” and find articles with reassuring titles like &lt;a href=&quot;https://medium.com/androiddevelopers/write-once-run-everywhere-tests-on-android-88adb2ba20c5&quot;&gt;Write Once, Run Everywhere Tests on Android&lt;/a&gt;. They say that I can just run the Espresso tests as local JVM tests!&lt;/p&gt;

&lt;p&gt;It seems that tests in the &lt;code&gt;androidTest&lt;/code&gt; source root will run on an external device / emulator when the test libraries are referenced with &lt;code&gt;androidTestImplementation&lt;/code&gt;, and the same code in the &lt;code&gt;test&lt;/code&gt; source root will run in a local JVM with &lt;code&gt;testImplementation&lt;/code&gt; libraries (including Robolectric). Oh, and a magic Gradle incantation, viz&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-groovy&quot;&gt;android {
    testOptions.unitTests.includeAndroidResources = true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This seems too good to be true, but I go ahead and add the &lt;code&gt;testImplementation&lt;/code&gt; declarations to my Gradle build file, giving me&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-groovy&quot;&gt;dependencies {
    // ...
    
    testImplementation 'junit:junit:4.12'

    // Core library
    testImplementation 'androidx.test:core:1.1.0'
    androidTestImplementation 'androidx.test:core:1.1.0'

    // AndroidJUnitRunner and JUnit Rules
    testImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    testImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    testImplementation 'androidx.test:rules:1.1.1'
    androidTestImplementation 'androidx.test:rules:1.1.1'

    // Espresso dependencies
    testImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

    testImplementation 'org.robolectric:robolectric:4.0'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By the way, I should say that this project is &lt;a href=&quot;https://github.com/dmcg/PressToTest&quot;&gt;available on GitHub&lt;/a&gt; if you want to see the full contents of files.&lt;/p&gt;

&lt;p&gt;Now I just copy my &lt;a href=&quot;https://github.com/dmcg/PressToTest/blob/1c92240b7a52d83c82102f760a07cb0ce9a82a74/app/src/androidTest/java/com/oneeeyedmen/presstotest/ExampleInstrumentedTest.kt&quot;&gt;ExampleInstrumentedTest&lt;/a&gt; into &lt;code&gt;src/test/java&lt;/code&gt; (along with its helper &lt;code&gt;Finger&lt;/code&gt; object).&lt;/p&gt;

&lt;p&gt;It’s here that things get a little weird. Android Studio is convinced that there are now two clashing &lt;code&gt;ExampleInstrumentedTest&lt;/code&gt;s, showing compilation errors in each, whereas Gradle is happy. As Android Studio just delegates to Gradle to run the tests these days, both versions of the tests can be run. When I do, I find that the emulator version (in &lt;code&gt;androidTest&lt;/code&gt;) continues to run and pass, whereas the JVM version (in &lt;code&gt;test&lt;/code&gt;) fails one of the two tests.&lt;/p&gt;

&lt;h2 id=&quot;hmmm&quot;&gt;Hmmm&lt;/h2&gt;

&lt;p&gt;In these situations my OCD doesn’t know which way to turn - I now have a broken test and a broken IDE (or at least IDE configuration). I decide that the latter is more fundamental - I need to trust that wiggley error lines are real when I see them.&lt;/p&gt;

&lt;p&gt;So I rename the &lt;code&gt;src/androidTest/java/com/oneeyedmen/presstotest/ExampleInstrumentedTest.kt&lt;/code&gt; to &lt;code&gt;ExternalInstrumentedTest&lt;/code&gt;, only to find that Android Studio renames &lt;code&gt;src/test/java/com/oneeyedmen/presstotest/ExampleInstrumentedTest.kt&lt;/code&gt; to &lt;code&gt;externalInstrumentedTest.kt&lt;/code&gt;. Yes, with a lower case &lt;code&gt;e&lt;/code&gt;. The Android Studio bug tracker is software only its mother could love, so I don’t know whether that’s a known issue, but I resort to Finder and BBEdit to fix the names and contents the old way and then find that the &lt;code&gt;Finger&lt;/code&gt; support object clashes even when I make it private in the test files.&lt;/p&gt;

&lt;p&gt;I eventually end up with &lt;a href=&quot;https://github.com/dmcg/PressToTest/commit/732f14dd749f308e71fb31a3a7b690b67ba585c2&quot;&gt;lots of code duplicated under different names&lt;/a&gt;, but at least all the squigglies have gone, so that I can relax into working out why the Robolectric test is failing.&lt;/p&gt;

&lt;h2 id=&quot;that-failing-test&quot;&gt;That Failing Test&lt;/h2&gt;

&lt;p&gt;The test that is failing is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun clicking_button_shows_temporary_BOOM_message() {

        onView(snackBarMatcher).check(doesNotExist())

        onView(buttonMatcher).perform(click())
        onView(snackBarMatcher).check(isDisplayed())

        Thread.sleep(3000)
        onView(snackBarMatcher).check(doesNotExist())
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;on the line after the &lt;code&gt;Thread.sleep&lt;/code&gt;, with the message &lt;code&gt;View is present in the hierarchy&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Long and bitter experience with UI toolkits has taught me that they often need cycles to properly update their state. To be honest I was surprised that just sleeping was enough to make this test pass on the emulator, so I’m more disappointed than shocked that it doesn’t work in Robolectric. Just in case I try a 6 second sleep, but that doesn’t help, so it’s off to Google again.&lt;/p&gt;

&lt;p&gt;That search results are frustrating. It seems that the snackbar wasn’t supported under Robolectric for quite a while, so that many of the results are people devising solutions to that problem. I &lt;em&gt;think&lt;/em&gt; that snackbar is now supported, in as much as the first two assertions pass, and suspect that the support just doesn’t extend to the auto-hide behaviour. Stepping through code in the debugger doesn’t seem to help one way or the other - the hiding responsibility seems split between a &lt;code&gt;SnackbarManager&lt;/code&gt; and a &lt;code&gt;Looper&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;After a couple of hours I’m about to give up when I try a last search for “robolectric looper” and come across a &lt;a href=&quot;https://stackoverflow.com/questions/34086857/robolectric-run-looper-of-handler-in-my-case&quot;&gt;Stack Overflow Answer&lt;/a&gt; that at least points the way towards&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun clicking_button_shows_temporary_BOOM_message() {

        onView(snackBarMatcher).check(doesNotExist())

        onView(buttonMatcher).perform(click())
        onView(snackBarMatcher).check(isDisplayed())

        ShadowLooper.idleMainLooper(3, TimeUnit.SECONDS)
        onView(snackBarMatcher).check(doesNotExist())
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Success! In fact it looks like I could use &lt;code&gt;ShadowLooper.runMainLooperToNextTask()&lt;/code&gt; without relying on a fixed time, but that would then cause internal and external test logic to diverge, which is undesirable. I’m pretty sure that if I understood what &lt;a href=&quot;https://medium.com/azimolabs/wait-for-it-idlingresource-and-conditionwatcher-602055f32356&quot;&gt;this article&lt;/a&gt; is saying I could find a common solution that does not have a fixed wait time - but I’m now worn out by the stress of having made so little progress for so long, so that’s a subject for another post.&lt;/p&gt;

&lt;h2 id=&quot;that-duplication&quot;&gt;That Duplication&lt;/h2&gt;

&lt;p&gt;Now I’m left with two structurally identical tests in two different source trees, where they can’t share the same code but can’t have the same names without confusing Android Studio.  I can’t make the &lt;code&gt;androidTest&lt;/code&gt; source depend on the &lt;code&gt;test&lt;/code&gt; source, because that would lead to Robolectric being mixed in to our external tests. A little more Googling comes up with this &lt;a href=&quot;https://stackoverflow.com/a/37882557/97777&quot;&gt;Stack Overflow Answer&lt;/a&gt;, and the following changes.&lt;/p&gt;

&lt;p&gt;In &lt;code&gt;build.gradle&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-groovy&quot;&gt;    sourceSets {
        String sharedTestDir = 'src/sharedTest/java'
        test {
            java.srcDir sharedTestDir
        }
        androidTest {
            java.srcDir sharedTestDir
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In &lt;code&gt;sharedTest&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
abstract class AcceptanceTests {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)

    @Test
    fun button_message_changes_on_pressing() {
        val button = onView(buttonMatcher)

        button.check(isDisplayed(withText(&quot;PRESS TO TEST&quot;)))

        button.perform(Finger.pressAndHold())
        button.check(isDisplayed(withText(&quot;RELEASE TO DETONATE&quot;)))

        button.perform(Finger.release())
        button.check(isDisplayed(withText(&quot;PRESS TO TEST&quot;)))
    }

    @Test
    fun clicking_button_shows_temporary_BOOM_message() {

        onView(snackBarMatcher).check(doesNotExist())

        onView(buttonMatcher).perform(click())
        onView(snackBarMatcher).check(isDisplayed())

        sleep(3000)
        onView(snackBarMatcher).check(doesNotExist())
    }

    protected abstract fun sleep(millis: Long)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In &lt;code&gt;test&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class InternalAcceptanceTests : AcceptanceTests() {
    override fun sleep(millis: Long) = ShadowLooper.idleMainLooper(millis, TimeUnit.MILLISECONDS)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In &lt;code&gt;androidTest&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class InstrumentedAcceptanceTests : AcceptanceTests() {
    override fun sleep(millis: Long) = Thread.sleep(millis)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;Today has been a lot more tiring than yesterday - lots of wallowing without any real idea if I can solve my problems. In the end though the result has been worth it - having the same tests running either in a local JVM or an emulator is a major productivity aid in real projects. The local JVM provides fast feedback when things are broken, while the instrumentation tests give confidence that app is actually in a state to ship.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;press-to-test-part-3.html&quot;&gt;Next time&lt;/a&gt;, I think I’ll probably look at true unit testing of our UI, breaking the dependency on Android.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Press to Test - Test Driven Development in Android Part 1</title>
   <link href="http://0.0.0.0:4000/press-to-test-part-1.html"/>
   <updated>2019-05-23T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/press-to-test-part-1</id>
   <content type="html">&lt;p&gt;This is Part 1 in a series documenting my experiences learning Android development in Kotlin.&lt;/p&gt;

&lt;p&gt;I’m going to start with a simple GUI toy that I have implemented in several GUI toolkits over the years - Press to Test.&lt;/p&gt;

&lt;h2 id=&quot;creating-the-project&quot;&gt;Creating the Project&lt;/h2&gt;

&lt;p&gt;This is my first Android project, so I have to install Android Studio and its tools, which takes some time. Once I can finally open the app I start by picking “Empty Activity” from the Android Studio “New Project” wizard, selecting a package for the source and leaving everything else as default. As a old &lt;a href=&quot;https://en.wikipedia.org/wiki/Extreme_programming&quot;&gt;XP&lt;/a&gt; developer I’m pleased to see that there are already two tests, an example unit test&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class ExampleUnitTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and an example instrumented test, designed to run on a device or emulator&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
    @Test
    fun useAppContext() {
        // Context of the app under test.
        val appContext = InstrumentationRegistry.getTargetContext()
        assertEquals(&quot;com.oneeyedmen.presstotest&quot;, appContext.packageName)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Oh, and there is an actual application too&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running this prompts me to create an emulator and then boots it up and runs the app, which due to some magic in &lt;code&gt;activity_main.xml&lt;/code&gt; draws “Hello World” in the middle of the simulated phone’s screen.&lt;/p&gt;

&lt;p&gt;The unit test runs and passes as expected, and impressively &lt;code&gt;ExampleInstrumentedTest&lt;/code&gt; also runs in Android Studio, installs the app on the emulator, and passes. As I was taught never to trust a test I hadn’t seen fail, I try breaking the test by changing the constant in &lt;code&gt;assertEquals&lt;/code&gt; and it obligingly fails with a nice stack trace in the Android Studio test runner.&lt;/p&gt;

&lt;p&gt;So far so good.&lt;/p&gt;

&lt;h2 id=&quot;cutting-myself-some-slack&quot;&gt;Cutting Myself Some Slack&lt;/h2&gt;

&lt;p&gt;Now I should write a failing test before adding any functionality. I &lt;em&gt;should&lt;/em&gt;, but I don’t actually know anything about Android development, let alone how to write sensible tests. Luckily XP has a get out - we can write a &lt;a href=&quot;http://www.extremeprogramming.org/rules/spike.html&quot;&gt;Spike&lt;/a&gt; to investigate how something might be done.&lt;/p&gt;

&lt;p&gt;But what is that I am trying to to do?&lt;/p&gt;

&lt;h2 id=&quot;the-requirement&quot;&gt;The Requirement&lt;/h2&gt;

&lt;p&gt;The app should show a single button with the label &lt;code&gt;Press to Test&lt;/code&gt;. When you press, but don’t release, the button, its label should change to &lt;code&gt;Release to Detonate&lt;/code&gt;. Releasing the button should result in some audiovisual extravaganza and reset the button for the next victim.&lt;/p&gt;

&lt;p&gt;I know right? How is there not already an app in the Play Store for this?&lt;/p&gt;

&lt;h2 id=&quot;spike&quot;&gt;Spike&lt;/h2&gt;

&lt;p&gt;I noodle around in the visual designer replacing the “Hello World” label with a “Press to Test” button, then look for how to implement the audiovisual extravaganza. Googling for “android show popup message” yields links for Toast and SnackBars and I arbitrarily choose the later as being more modern, probably. More Googling, this time for “android button click event” and I cobble together the following.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener { view -&amp;gt;
            Snackbar.make(view, &quot;BOOM!&quot;, Snackbar.LENGTH_SHORT)
                .setAction(&quot;Action&quot;, null).show()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is what my friend Richard Care would describe as “monkey-see, monkey-do” code. In particular I have no real idea where &lt;code&gt;R.layout.activity_main&lt;/code&gt; and &lt;code&gt;button&lt;/code&gt; come from, except for some theory that code is being generated to reflect the contents of resource XML files. But no matter, because it works.&lt;/p&gt;

&lt;p align=&quot;center&quot;&gt;&lt;img alt=&quot;Here's the kaboom&quot; src=&quot;assets/press-to-test-1.gif&quot; height=&quot;480&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;now-for-that-test&quot;&gt;Now For That Test&lt;/h2&gt;

&lt;p&gt;I suspect that there might be ways to test our UI in unit tests, with &lt;a href=&quot;http://robolectric.org/&quot;&gt;fake bits of Android&lt;/a&gt;, but there’s nothing like the reassurance of a test that actually runs on a device, albeit an emulated one. So I Google for “Android UI testing” and find &lt;a href=&quot;https://developer.android.com/training/testing/espresso&quot;&gt;Espresso&lt;/a&gt; is the recommended approach. Except that when I look at the latest examples, they seem to using different packages than the example code generated by Android Studio. In the end I plump for using &lt;code&gt;androidx.test&lt;/code&gt; by &lt;a href=&quot;https://github.com/dmcg/PressToTest/commit/baaf3600f0055e054ea1a53592bd87806bc4ac3c&quot;&gt;updating a whole bunch of referenced libraries&lt;/a&gt; and Googling for the errors caused until they went away.&lt;/p&gt;

&lt;p&gt;Armed with Espresso, I can launch my activity (although I’m not clear why that is different from running the app) and press the button in code.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;import androidx.test.InstrumentationRegistry
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.ActivityTestRule

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import org.junit.Rule

@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)

    @Test
    fun click_button() {
        Espresso.onView(withId(R.id.button)).perform(click())
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When I run this in Android Studio, the emulator helpfully reacts and shows the snackbar, so that gives lots of confidence that we’re on the right track.&lt;/p&gt;

&lt;p&gt;Now more Googling for how to find and check the snackbar, leading after about half an hour of experiments to the following&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)

    @Test
    fun click_button() {
        val snackBarMatcher = allOf(
            withId(android.support.design.R.id.snackbar_text),
            withText(&quot;BOOM!&quot;)
        )

        onView(snackBarMatcher).check(doesNotExist())

        onView(withId(R.id.button)).perform(click())
        onView(snackBarMatcher).check(matches(isDisplayed()))

        Thread.sleep(3000)
        onView(snackBarMatcher).check(doesNotExist())
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hey that’s not at all bad. Espresso seems well thought out, and although the &lt;code&gt;Thread.sleep&lt;/code&gt; is a bit icky I can live with it for now. The test name is bad, but it will get sorted out when we have more context too. I guess we should call the end of our spike and settle down into TDD.&lt;/p&gt;

&lt;h2 id=&quot;the-button-text&quot;&gt;The Button Text&lt;/h2&gt;

&lt;p&gt;The only thing that our app doesn’t do (assuming you have a low extravaganza-threshold) is change the button text. Before implementing that, I work out how to check the text in a test, and refactor the existing test a little.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)

    @Test
    fun button_message_changes_on_pressing() {
        onView(buttonMatcher).check(matches(
            allOf(
                isDisplayed(),
                withText(&quot;PRESS TO TEST&quot;)
            )))
    }

    @Test
    fun clicking_button_shows_temporary_BOOM_message() {

        onView(snackBarMatcher).check(doesNotExist())

        onView(buttonMatcher).perform(click())
        onView(snackBarMatcher).check(matches(isDisplayed()))

        Thread.sleep(3000)
        onView(snackBarMatcher).check(doesNotExist())
    }
}

private val buttonMatcher = withId(R.id.button)

private val snackBarMatcher = allOf(
    withId(android.support.design.R.id.snackbar_text),
    withText(&quot;BOOM!&quot;)
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we’re fully into test-first mode, I go looking for how to &lt;a href=&quot;https://stackoverflow.com/questions/32010927/android-espresso-make-assertion-while-button-is-kept-pressed&quot;&gt;test touch down and touch up interactions in Espresso&lt;/a&gt;. Copying and pasting the code from the answer into a &lt;a href=&quot;https://github.com/dmcg/PressToTest/blob/7d4228fc1dc34a98a3994cd1056cdff9eca54ecb/app/src/androidTest/java/com/oneeeyedmen/presstotest/Finger.kt&quot;&gt;Finger object&lt;/a&gt; let’s me write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun button_message_changes_on_pressing() {
        onView(buttonMatcher).check(matches(
            allOf(
                isDisplayed(),
                withText(&quot;PRESS TO TEST&quot;)
            )))

        onView(buttonMatcher).perform(Finger.pressAndHold())
        onView(buttonMatcher).check(matches(
            allOf(
                isDisplayed(),
                withText(&quot;RELEASE TO DETONATE&quot;)
            )))

        onView(buttonMatcher).perform(Finger.release())
        onView(buttonMatcher).check(matches(
            allOf(
                isDisplayed(),
                withText(&quot;PRESS TO TEST&quot;)
            )))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which isn’t pretty but does fail, so I can write some production code. More Googling reveals &lt;code&gt;setOnTouchListener&lt;/code&gt;, allowing me to cobble together the following&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnTouchListener { view, event -&amp;gt;
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -&amp;gt; button.text = &quot;RELEASE TO DETONATE&quot;
                MotionEvent.ACTION_UP -&amp;gt; button.text = &quot;PRESS TO TEST&quot;
            }
            true
        }

        button.setOnClickListener { view -&amp;gt;
            Snackbar.make(view, &quot;BOOM!&quot;, Snackbar.LENGTH_SHORT)
                .setAction(&quot;Action&quot;, null).show()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Build it, run the tests and get home in time for tea and medals. Except that the &lt;code&gt;button_message_changes_on_pressing&lt;/code&gt; fails. I’m used to this though - knowing UI tests it’s probably some timing issue. So I run the app in the emulator, and find that, in fact, our earth-shattering kaboom &lt;em&gt;is&lt;/em&gt; missing.&lt;/p&gt;

&lt;p&gt;Running the test again shows that Espresso was trying to tell me that&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (with id: com.oneeyedmen.presstotest:id/snackbar_text and with text: is &quot;BOOM!&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;along with a really handy dump of the whole view hierarchy. Well, it isn’t handy now, but I can see it being very useful when debugging problems where a view is present but invisible, or sitting under the wrong parent.&lt;/p&gt;

&lt;p&gt;Luckily it doesn’t take long to realise that the problem is that returning &lt;code&gt;true&lt;/code&gt; from the touch listener is telling Android that we have handled the event, so it isn’t processing the &lt;em&gt;up&lt;/em&gt; to make a click. Return &lt;code&gt;false&lt;/code&gt;, and the tests both pass. Not only that, but the app actually works!&lt;/p&gt;

&lt;p align=&quot;center&quot;&gt;&lt;img alt=&quot;Here's another kaboom&quot; src=&quot;assets/press-to-test-2.gif&quot; height=&quot;480&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;tidy-up&quot;&gt;Tidy Up&lt;/h2&gt;

&lt;p&gt;All that’s required is a little test tidy up&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java)

    @Test
    fun button_message_changes_on_pressing() {
        val button = onView(buttonMatcher)

        button.check(isDisplayed(withText(&quot;PRESS TO TEST&quot;)))

        button.perform(Finger.pressAndHold())
        button.check(isDisplayed(withText(&quot;RELEASE TO DETONATE&quot;)))

        button.perform(Finger.release())
        button.check(isDisplayed(withText(&quot;PRESS TO TEST&quot;)))
    }

    @Test
    fun clicking_button_shows_temporary_BOOM_message() {

        onView(snackBarMatcher).check(doesNotExist())

        onView(buttonMatcher).perform(click())
        onView(snackBarMatcher).check(isDisplayed())

        Thread.sleep(3000)
        onView(snackBarMatcher).check(doesNotExist())
    }
}

private val buttonMatcher = withId(R.id.button)

private val snackBarMatcher = allOf(
    withId(android.support.design.R.id.snackbar_text),
    withText(&quot;BOOM!&quot;)
)

private fun isDisplayed(matcher: Matcher&amp;lt;View&amp;gt; = Matchers.any(View::class.java)) = matches(
    allOf(
        ViewMatchers.isDisplayed(),
        matcher
    )
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we’re done for the day.&lt;/p&gt;

&lt;h2 id=&quot;wrap-up&quot;&gt;Wrap Up&lt;/h2&gt;

&lt;p&gt;Running tests on the emulator is remarkably painless with Android Studio. Each one does take a couple of seconds though, so it would be nice to be able to test our logic as part of unit tests run in a nice fast Gradle test VM instance. In the &lt;a href=&quot;press-to-test-part-2.html&quot;&gt;next installment&lt;/a&gt; I’ll take a look at that.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>My New Test Model</title>
   <link href="http://0.0.0.0:4000/my-new-test-model.html"/>
   <updated>2019-03-29T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/my-new-test-model</id>
   <content type="html">&lt;h2 id=&quot;abstract&quot;&gt;Abstract&lt;/h2&gt;

&lt;p&gt;I examine the strengths and weaknesses of the The xUnit and Spec testing models in terms of expressiveness, extensibility and their ability to reuse test code. I then propose a revised model which, by treating fixtures as a first-class abstraction, significantly improves on the existing frameworks.&lt;/p&gt;

&lt;h2 id=&quot;introduction&quot;&gt;Introduction&lt;/h2&gt;

&lt;p&gt;The xUnit family of testing frameworks was started by Kent Beck with &lt;a href=&quot;http://swing.fit.cvut.cz/projects/stx/doc/online/english/tools/misc/testfram.htm&quot;&gt;SUnit&lt;/a&gt; in 1989. It defines tests as methods of a class, and the test fixture as fields of that class. This model is simple and well suited to &lt;a href=&quot;https://en.wikipedia.org/wiki/Test-driven_development&quot;&gt;Test Driven Development&lt;/a&gt;, but in my experience is neither very expressive nor easily extensible.&lt;/p&gt;

&lt;p&gt;Spec (for specification) testing introduced a more expressive language in order be readable by less technical people as part of &lt;a href=&quot;https://en.wikipedia.org/wiki/Behavior-driven_development&quot;&gt;Behaviour Driven Development&lt;/a&gt;. Its model is also more extensible than xUnit’s, but at the expense of significant complication in the management of test fixtures.&lt;/p&gt;

&lt;p&gt;As a long time JUnit (and occasional RSpec, unittest and Jasmine) user, neither model fully meets all my needs. I write tests to drive designs, document code, demonstrate system behaviour, prevent regressions and find existing bugs; but existing test tools don’t to allow me to flow between these roles, or to reuse test code in different modes.&lt;/p&gt;

&lt;p&gt;This paper explores the difficulties that I have with the xUnit and Spec models and proposes a revised model that works significantly better for me.&lt;/p&gt;

&lt;h2 id=&quot;fixtures&quot;&gt;Fixtures&lt;/h2&gt;

&lt;p&gt;A lot of the discussion that follows will revolve around test fixtures. What are they?&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Test_fixture&quot;&gt;Wikipedia&lt;/a&gt; says:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A test fixture is something used to consistently test some item, device, or piece of software. Test fixtures can be found when testing electronics, software and physical devices.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The &lt;a href=&quot;https://github.com/junit-team/junit4/wiki/test-fixtures&quot;&gt;JUnit 4 Wiki&lt;/a&gt; says:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;A test fixture is a fixed state of a set of objects used as a baseline for running tests. The purpose of a test fixture is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So a test fixture is something to give us consistency / repeatability. In software we try where possible to create a fixture that encapsulates all the state that can affect the result of running the test, or is affected by the running of the test. That way, by creating a fresh fixture for each test, we can prevent one test run from affecting a later one.&lt;/p&gt;

&lt;p&gt;There is a notable difference between a physical test fixture and a software test fixture. When testing a physical part it is mounted &lt;em&gt;in&lt;/em&gt; the fixture - they are separate. When testing a software object, then the fixture will generally create that object - the subject under test will be a property of the fixture. This isn’t a hard and fast rule though; in particular when testing stateless objects, stand-alone functions, or external services.&lt;/p&gt;

&lt;h2 id=&quot;xunit&quot;&gt;xUnit&lt;/h2&gt;

&lt;p&gt;The xUnit lineage of test frameworks began with SUnit. SUnit’s model was to compose a fixture from the instance variables of a class, so that independent fixtures can be created by creating a new instance of the class. Tests are then written as methods on that class, and can reference the fixture as their own instance variables.&lt;/p&gt;

&lt;p&gt;This model was carried forward to JUnit, NUnit and all the xUnits. Here is a (pedagogically stilted) JUnit test, written in Kotlin, for a function to move the contexts of one mutable list into another.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MoveIntoTests {

    // the subjects under test
    lateinit var source: MutableList&amp;lt;String&amp;gt;
    lateinit var destination: MutableList&amp;lt;String&amp;gt;

    @Test
    fun `empty list to empty list`() {
        source = emptyMutableList()
        destination = emptyMutableList()
        moveInto(source, destination)
        assertEquals(emptyMutableList(), destination)
    }

    @Test
    fun `empty list to non-empty list`() {
        source = emptyMutableList()
        destination = aNonEmptyList.toMutableList()
        moveInto(source, destination)
        assertEquals(aNonEmptyList, destination)
    }

    @Test
    fun `non-empty list to empty list`() {
        source = aNonEmptyList.toMutableList()
        destination = emptyMutableList()
        moveInto(source, destination)
        assertEquals(aNonEmptyList, destination)
    }

    @Test
    fun `non-empty list to non-empty list`() {
        source = aNonEmptyList.toMutableList()
        destination = aNonEmptyListToo.toMutableList()
        moveInto(source, destination)
        assertEquals(aNonEmptyListToo + aNonEmptyList, destination)
    }

    @AfterEach
    fun `source should be empty`() {
        assertEquals(emptyMutableList(), source)
    }
}

private var aNonEmptyList = listOf(&quot;apple&quot;)
private var aNonEmptyListToo = listOf(&quot;banana&quot;, &quot;cherry&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the two subjects under test (&lt;code&gt;source&lt;/code&gt; and &lt;code&gt;destination&lt;/code&gt;) are properties of the test class and hence form the fixture. To run the tests, JUnit collects all the methods annotated with &lt;code&gt;@Test&lt;/code&gt; and, for each, it creates an instance of the test class and then invokes the particular test method. In this way our tests can mutate the components of the fixture safe in the knowledge that the next test will have a fresh copy.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;nonEmptyList1&lt;/code&gt; and &lt;code&gt;nonEmptyList2&lt;/code&gt; might ordinarily be properties and so also part of the fixture. In this case I have moved them into the top level scope to emphasise that, as immutable collections of immutable values, they can be shared between tests without cross-contamination of state.&lt;/p&gt;

&lt;p&gt;This is a nice simple model, but it has some limitations.&lt;/p&gt;

&lt;h2 id=&quot;xunit-tests-are-defined-by-methods&quot;&gt;xUnit Tests are Defined by Methods&lt;/h2&gt;

&lt;p&gt;Having tests defined as methods means that more tests need more methods - or special treatment. Consider repeating a test a number of times - the test framework has to provide a mechanism for this, as we can’t (in most static languages) define test methods at runtime. JUnit 5 has a &lt;a href=&quot;https://junit.org/junit5/docs/current/user-guide/#writing-tests-repeated-tests&quot;&gt;@RepeatedTest&lt;/a&gt; annotation to allow us to do this. If we want to check that &lt;code&gt;empty list to empty list&lt;/code&gt; &lt;em&gt;really&lt;/em&gt; behaves as expected we can write something like&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RepeatedTest(value = 100, name = &quot;attempt {currentRepetition}&quot;)
fun `empty list to empty list`() {
    source = emptyMutableList()
    destination = emptyMutableList()
    moveInto(source, destination)
    assertEquals(emptyMutableList(), destination)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but &lt;code&gt;RepeatedTest&lt;/code&gt;is a facility that the JUnit authors had to provide - I couldn’t implement it myself. I know how to repeat things in Kotlin, but every time I want to repeat tests in JUnit I have to look up how to cast this magic spell.&lt;/p&gt;

&lt;p&gt;How about repeating a test with different parameters? Again there is an annotation &lt;a href=&quot;https://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests&quot;&gt;@ParameterizedTest&lt;/a&gt;, and again it is very much a special case rather than something that I as a test author could write given the model of the test framework.&lt;/p&gt;

&lt;p&gt;Even something as simple as &lt;em&gt;not&lt;/em&gt; running a test requires framework support. JUnit 5 ends up with an &lt;code&gt;@Disabled&lt;/code&gt; annotation, plus &lt;code&gt;@DisabledOnOs&lt;/code&gt;, &lt;code&gt;@DisabledIfSystemProperty&lt;/code&gt;, &lt;code&gt;@DisabledIfEnvironmentVariable&lt;/code&gt;, &lt;code&gt;@DisabledIf&lt;/code&gt; - which can evaluate Javascript expressions but not (out of the box) the language in which I am actually writing the tests, and finally an entire &lt;code&gt;ExecutionCondition&lt;/code&gt; extension API.&lt;/p&gt;

&lt;p&gt;These limitations are caused by using methods as the way of defining tests, without providing any good way to treat them as first-class units of execution. There have been attempts to address this - JUnit 4 introduced &lt;a href=&quot;https://junit.org/junit4/javadoc/4.12/org/junit/rules/TestRule.html&quot;&gt;TestRules&lt;/a&gt; -&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;an alteration in how a test method, or set of test methods, is run and reported.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;and &lt;a href=&quot;https://junit.org/junit4/javadoc/4.12/org/junit/experimental/theories/Theories.html&quot;&gt;Theories&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The Theories runner allows to test a certain functionality against a subset of an infinite set of data points.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;but these are both object-oriented knives in what should be a functional gunfight. The most promising avenue is JUnit 5’s &lt;a href=&quot;https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests&quot;&gt;Dynamic Tests&lt;/a&gt;; unfortunately this appears to be a completely different execution model to the rest of the framework and so does not integrate well with ‘normal’ tests.&lt;/p&gt;

&lt;h2 id=&quot;only-one-fixture-setup-per-xunit-class&quot;&gt;Only One Fixture Setup per xUnit Class&lt;/h2&gt;

&lt;p&gt;Another limitation with the xUnit model is that every test in a class shares the same fixture setup code. In our example &lt;code&gt;source&lt;/code&gt; and &lt;code&gt;destination&lt;/code&gt; need to be initialised differently for each test, so each test has to do that initialisation. This leads to the ugliness of the &lt;code&gt;lateinit&lt;/code&gt; - our way of telling Kotlin that someone will populate that value &lt;a href=&quot;https://www.urbandictionary.com/define.php?term=dreckly&quot;&gt;dreckly&lt;/a&gt;. An alternative is to create a different test class for each initial fixture state, or to &lt;a href=&quot;https://junit.org/junit5/docs/current/user-guide/#writing-tests-nested&quot;&gt;nest classes&lt;/a&gt; to express context. Both are not the standard model and take significant effort to maintain.&lt;/p&gt;

&lt;p&gt;This might not seem like a major problem, but tests are often trying to do the difficult job of communicating to a human how a complicated system will behave in different circumstances. When that communication is through examples it is important for the human to be able to see the commonality and difference between the examples without expending precious mental bandwidth.&lt;/p&gt;

&lt;p&gt;The quest for tests so expressive that product owners could understand what they are telling us about the behaviour of our systems motivated the creation of another test framework family, the Specs.&lt;/p&gt;

&lt;h2 id=&quot;specifications-bring-structure&quot;&gt;Spec(ification)s Bring Structure&lt;/h2&gt;

&lt;p&gt;Spec-like frameworks, beginning I believe with &lt;a href=&quot;http://rspec.info/&quot;&gt;RSpec&lt;/a&gt;, allow us to demonstrate behaviour in different contexts. In the Kotlin framework &lt;a href=&quot;https://spekframework.org&quot;&gt;Spek&lt;/a&gt; our previous example might look like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object MoveIntoSpec : Spek({

    describe(&quot;moveInto&quot;) {
        context(&quot;empty list to empty list&quot;) {
            val source = emptyMutableList()
            val destination = emptyMutableList()

            it(&quot;should not change source or destination&quot;) {
                moveInto(source, destination)
                assertEquals(emptyMutableList(), destination)
                assertEquals(emptyMutableList(), source)
            }
        }

        context(&quot;empty list to non-empty list&quot;) {
            val source = emptyMutableList()
            val destination = aNonEmptyList.toMutableList()

            it(&quot;should not change source or destination&quot;) {
                moveInto(source, destination)
                assertEquals(aNonEmptyList, destination)
                assertEquals(emptyMutableList(), source)
            }
        }

        context(&quot;non-empty list to empty list&quot;) {
            val source = aNonEmptyList.toMutableList()
            val destination = emptyMutableList()

            it(&quot;should move source items into destination&quot;) {
                moveInto(source, destination)
                assertEquals(aNonEmptyList, destination)
                assertEquals(emptyMutableList(), source)
            }
        }

        context(&quot;non-empty list to non-empty list&quot;) {
            val source = aNonEmptyList.toMutableList()
            val destination = aNonEmptyListToo.toMutableList()

            it(&quot;should move source items into destination&quot;) {
                moveInto(source, destination)
                assertEquals(aNonEmptyListToo + aNonEmptyList, destination)
                assertEquals(emptyMutableList(), source)
            }
        }
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Look at how the variable parts of the fixture, &lt;code&gt;source&lt;/code&gt; and &lt;code&gt;destination&lt;/code&gt;, agree with the context description. We have named a context and expressed it in code. This structure is difficult to impose with xUnit frameworks, but is the point of specs. xUnit only allows a single fixture setup and then we’re straight into tests - here different contexts can set up the fixtures in different ways before their tests are run. Specs allow the Given of Given When Then to be expressed in the context structure.&lt;/p&gt;

&lt;h2 id=&quot;specs-are-dynamic&quot;&gt;Specs are Dynamic&lt;/h2&gt;

&lt;p&gt;A convenient side-effect of the Spec model is that those &lt;code&gt;context&lt;/code&gt; and &lt;code&gt;it&lt;/code&gt; blocks are evaluated at runtime, which means that in Spek, if I want to be &lt;em&gt;really&lt;/em&gt; sure that moving an empty list into an empty list results in an empty list, I can just write plain old code to repeatedly create tests.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;context(&quot;empty list to empty list&quot;) {
    val source = emptyMutableList()
    val destination = emptyMutableList()

    (1..100).forEach { run -&amp;gt;
        it(&quot;should not change source or destination attempt $run&quot;) {
            moveInto(source, destination)
            assertEquals(emptyMutableList(), destination)
            assertEquals(emptyMutableList(), source)
        }
    }
}
// Note that we will see later that this test is logically flawed
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Parameterised tests are almost as easy to write in Spec-like frameworks. As we will see later - no need to look up what magic annotations your framework authors have conjured up - just define a source of parameter values and create contexts or tests on the fly for whatever combinations you like. Compared to xUnit our tests (and contexts) have been promoted to first-class status, so that we can bring the tools of functional programming to bear.&lt;/p&gt;

&lt;p&gt;There are problems hiding in those contexts though.&lt;/p&gt;

&lt;h2 id=&quot;spec-fixture-lifecycle&quot;&gt;Spec Fixture Lifecycle&lt;/h2&gt;

&lt;p&gt;Your obsessive-compulsive side might think that there should be two levels of nested contexts in this example, so that we can better express their commonality and difference. As someone who just had to look up whether to hyphenate obsessive-compulsive, I agree.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object MoveIntoNestedSpec : Spek({
    describe(&quot;moveInto&quot;) {
        context(&quot;empty source&quot;) {
            val source = emptyMutableList()

            context(&quot;empty destination&quot;) {
                val destination = emptyMutableList()

                it(&quot;should not change destination&quot;) {
                    moveInto(source, destination)
                    assertEquals(emptyMutableList(), destination)
                }
            }
            context(&quot;non-empty destination&quot;) {
                val destination = aNonEmptyList.toMutableList()

                it(&quot;should not change destination&quot;) {
                    moveInto(source, destination)
                    assertEquals(aNonEmptyList, destination)
                }
            }

            afterEach {
                // source should always be emptied
                assertEquals(emptyMutableList(), source)
            }
        }

        context(&quot;non-empty source&quot;) {
            val source = aNonEmptyList.toMutableList()

            context(&quot;empty destination&quot;) {
                val destination = emptyMutableList()

                it(&quot;should contain just the source&quot;) {
                    moveInto(source, destination)
                    assertEquals(aNonEmptyList, destination)
                }
            }

            context(&quot;non-empty destination&quot;) {
                val destination = aNonEmptyListToo.toMutableList()

                it(&quot;should contain destination plus source&quot;) {
                    moveInto(source, destination)
                    assertEquals(aNonEmptyListToo + aNonEmptyList, destination)
                }
            }

            afterEach {
                assertEquals(emptyMutableList(), source)
            }
        }
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ah - that’s so much better.&lt;/p&gt;

&lt;p&gt;It’s such a shame that it doesn’t work.&lt;/p&gt;

&lt;p&gt;The problem is that those &lt;code&gt;source&lt;/code&gt; variables are shared between the child contexts and are mutable. In the &lt;code&gt;non-empty source&lt;/code&gt; context, &lt;code&gt;val source = nonEmptyList1.toMutableList()&lt;/code&gt; is executed only once, when the contexts are being defined, before running the tests. So &lt;code&gt;should contain destination plus source&lt;/code&gt; finds that &lt;code&gt;source&lt;/code&gt; has been cleared out by the previous test and there is nothing to add.&lt;/p&gt;

&lt;p&gt;There are two common solutions to this problem in Spec-like tests. The first is the use of &lt;code&gt;before&lt;/code&gt; blocks to initialise mutable fixture state&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;context(&quot;non-empty source&quot;) {
    lateinit var source: MutableList&amp;lt;String&amp;gt;
    beforeEach {
        source = aNonEmptyList.toMutableList()
    }
    //...

    context(&quot;non-empty destination&quot;) {
        lateinit var destination: MutableList&amp;lt;String&amp;gt;
        beforeEach {
            destination = aNonEmptyListToo.toMutableList()
        }

        it(&quot;should contain destination plus source&quot;) {
            moveInto(source, destination)
            assertEquals(aNonEmptyListToo + aNonEmptyList, destination)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second is the use of a special lazy construct - Spek calls this &lt;code&gt;memoized&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;context(&quot;non-empty source&quot;) {
    val source by memoized { aNonEmptyList.toMutableList() }

    //...
    context(&quot;non-empty destination&quot;) {
        val destination by memoized { aNonEmptyListToo.toMutableList() }

        it(&quot;should contain destination plus source&quot;) {
            moveInto(source, destination)
            assertEquals(aNonEmptyListToo + aNonEmptyList, destination)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;beforeEach&lt;/code&gt; method is tedious, error-prone, and doesn’t sit well with an immutable, functional style. Initialisation blocks like memoized are nicer, but force users to internalise the test lifecycle and differentiate between the handling of mutable and immutable state. Everything can appear to be fine until you add a test, or reorder what is there, and the tests that were passing now fail.&lt;/p&gt;

&lt;h2 id=&quot;spec-fixture-scope&quot;&gt;Spec Fixture Scope&lt;/h2&gt;

&lt;p&gt;Another problem with the Spec model is that tests rely on receiving the fixture properties in their lexical scope. As a result extracting common code and reusing it between tests is hard, at least in statically typed languages. If you try to extract &lt;code&gt;it(&quot;should contain destination plus source&quot;)&lt;/code&gt; for use in another test you’ll find it is tied into place by &lt;code&gt;source&lt;/code&gt; and &lt;code&gt;destination&lt;/code&gt;. In xUnit, where the fixture has a type (the type of the test class), we routinely extract a supertype with the fixture properties and methods that rely on these properties. Concrete classes can then inherit from this to share fixtures, setup, tests and utilities. We can’t do that in the Spec model, so have to fall back on framework-provided &lt;a href=&quot;https://spekframework.github.io/spek/docs/latest/#_subjects&quot;&gt;special cases&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;the-best-of-both-worlds&quot;&gt;The Best of Both Worlds&lt;/h2&gt;

&lt;p&gt;In summary: xUnit has a simple fixture model that we can understand and reuse, but limited facilities for expressing fixture variations, and poor support for manipulating tests as first class constructs; Specs address these limitations of xUnit, but at the expense of a complicated and not easily reusable fixture model.&lt;/p&gt;

&lt;p&gt;What if we could combine the nested scopes and programmatic test generation of the Spec model with the simple and predictable fixtures of the xUnit system? We would then be able to execute business-friendly specs and security-friendly fuzz testing. We could run a test for every file in a directory of examples or skip a test every Tuesday afternoon without recourse to the framework manual. And we would be able to combine test contracts into suites of tests for concrete implementations.&lt;/p&gt;

&lt;h2 id=&quot;try-this-one-weird-trick&quot;&gt;Try this One Weird Trick&lt;/h2&gt;

&lt;p&gt;The key to these benefits is to promote the fixture to a first-class abstraction, separate from the tests.&lt;/p&gt;

&lt;p&gt;There are two aspects to this promotion. The first aspect is type, the second lifecycle. In xUnit the type of the fixture is the type of the test class, and they share the same lifecycle. In Specs, the fixture lifecycle is decoupled from the test lifecycle, but there is no separate fixture type.&lt;/p&gt;

&lt;p&gt;Let’s see what happens when we extract a fixture type in our nested context Spek test.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object MoveIntoNestedFixtureSpec : Spek({

    // Create a fixture class with all our mutable test state
    data class Fixture(
        val source: MutableList&amp;lt;String&amp;gt; = emptyMutableList(),
        val destination: MutableList&amp;lt;String&amp;gt; = emptyMutableList()
    )

    describe(&quot;moveInto&quot;) {
        //...
        context(&quot;non-empty source&quot;) {
            val fixture by memoized {
                Fixture(aNonEmptyList.toMutableList())
            }

            context(&quot;empty destination&quot;) {
                it(&quot;should contain just the source&quot;) {
                    moveInto(fixture.source, fixture.destination)
                    assertEquals(aNonEmptyList, fixture.destination)
                }
            }

            context(&quot;non-empty destination&quot;) {
                val fixture by memoized {
                    fixture.copy(destination = aNonEmptyListToo.toMutableList())
                    // ↑ this fixture is the parent fixture
                }
                it(&quot;should contain destination plus source&quot;) {
                    moveInto(fixture.source, fixture.destination)
                    assertEquals(aNonEmptyListToo + aNonEmptyList, fixture.destination)
                }
            }

            afterEach {
                assertEquals(emptyMutableList(), fixture.source)
            }
        }
    }
})
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In exchange for explicitly creating and managing the fixture down the context tree, we have a simple rule - if a test references a mutable thing, either in setup or execution, initialise that thing in the fixture and initialise the fixture in a &lt;code&gt;by memoized&lt;/code&gt; block.&lt;/p&gt;

&lt;p&gt;Now that the fixture has its own type, you can also see that the tests and common setup code can be extracted and reused, as they now depend only on &lt;code&gt;Fixture&lt;/code&gt; (and constants).&lt;/p&gt;

&lt;p&gt;The downside of this approach is the irritation of not having access to the fixture properties without qualification - &lt;code&gt;fixture.source.moveInto(fixture.destination)&lt;/code&gt; gets old pretty quickly compared to having the properties directly in scope. If we could solve that problem then this model could meet our design goal of having the flexibility and expressiveness of a Spec with the predictable model and fixture reuse of an xUnit.&lt;/p&gt;

&lt;h2 id=&quot;introducing-minutest&quot;&gt;Introducing Minutest&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/dmcg/minutest&quot;&gt;Minutest&lt;/a&gt; is a Kotlin library created to explore this approach. It takes advantage of a Kotlin language feature that allows the value of the implicit receiver &lt;code&gt;this&lt;/code&gt; to be provided by framework code. Because fixtures are special, in that there will only be one instance per test, Minutest allows the test developer to specify how to create, mutate and translate the single instance in contexts, and then returns it to the tests as the implicit receiver.&lt;/p&gt;

&lt;p&gt;Let’s look at our contexts in Minutest.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MoveIntoMinutests : JUnit5Minutests {

    data class Fixture(
        val source: MutableList&amp;lt;String&amp;gt; = emptyMutableList(),
        val destination: MutableList&amp;lt;String&amp;gt; = emptyMutableList()
    )

    fun tests() = rootContext&amp;lt;Fixture&amp;gt; // Contexts are parameterised by the fixture type
    {
        context(&quot;empty source&quot;) {

            // The fixture block is run once per test and must return an instance of the fixture
            fixture {
                Fixture(emptyMutableList(), emptyMutableList())
            }

            context(&quot;empty destination&quot;) {
                test(&quot;should not be changed&quot;) {
                    // here 'this' is the fixture inherited from the 'empty source'
                    moveInto(source, destination)
                    assertEquals(emptyMutableList(), destination)
                }
            }

            context(&quot;non-empty destination&quot;) {

                // the deriveFixture block translates from the parent fixture
                deriveFixture {
                    parentFixture.copy(destination = aNonEmptyList.toMutableList())
                }

                test(&quot;should not be changed&quot;) {
                    moveInto(source, destination)
                    assertEquals(aNonEmptyList, destination)
                }
            }

            after {
                // after blocks also have the fixture as 'this'
                assertEquals(emptyMutableList(), source)
            }
        }

        context(&quot;non-empty source&quot;) {
            fixture {
                Fixture(aNonEmptyList.toMutableList())
            }

            context(&quot;empty destination&quot;) {
                test(&quot;should contain just the source&quot;) {
                    moveInto(source, destination)
                    assertEquals(aNonEmptyList, destination)
                }
            }

            context(&quot;non-empty destination&quot;) {
                deriveFixture {
                    parentFixture.copy(destination = aNonEmptyListToo.toMutableList())
                }

                test(&quot;should contain destination plus source&quot;) {
                    moveInto(source, destination)
                    assertEquals(aNonEmptyListToo + aNonEmptyList, destination)
                }
            }

            after {
                assertEquals(emptyMutableList(), source)
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the &lt;code&gt;fixture&lt;/code&gt; block is called by the framework once for each test, so that stateful fixtures will not contaminate future tests. &lt;code&gt;deriveFixture&lt;/code&gt; allows a context to change the fixture from its parent. All &lt;code&gt;fixture&lt;/code&gt;, &lt;code&gt;test&lt;/code&gt; and &lt;code&gt;before&lt;/code&gt; and &lt;code&gt;after&lt;/code&gt; blocks have access to the value of the fixture in their context as &lt;code&gt;this&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This model has proved to be both expressive and flexible. As a Spec, Minutest allows easy manipulation of contexts and tests, so that we can quickly refactor the previous example to a parameterised test without having to look up how to use a special annotation.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MoveIntoParameterisedMinutests : JUnit5Minutests {

    data class Fixture(
        val source: MutableList&amp;lt;String&amp;gt; = emptyMutableList(),
        val destination: MutableList&amp;lt;String&amp;gt; = emptyMutableList()
    ) {
        override fun toString() = &quot;$source and $destination&quot;
    }

    val scenarios = listOf(
        Fixture(emptyMutableList(), emptyMutableList()),
        Fixture(aNonEmptyList.toMutableList(), emptyMutableList()),
        Fixture(emptyMutableList(), aNonEmptyListToo.toMutableList()),
        Fixture(aNonEmptyList.toMutableList(), aNonEmptyListToo.toMutableList())
    )

    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        scenarios.forEach { scenario -&amp;gt;
            context(&quot;Given $scenario&quot;) {
                fixture {
                    scenario
                }
                test(&quot;moves items from source to destination&quot;) {
                    val originalSource = source.toList()
                    val originalDestination = destination.toList()
                    moveInto(source, destination)
                    assertEquals(originalDestination + originalSource, destination)
                    assertEquals(emptyMutableList(), source)
                }
            }

            willRun(
                &quot;root&quot;,
                &quot;  Given [] and []&quot;,
                &quot;    moves items from source to destination&quot;,
                &quot;  Given [apple] and []&quot;,
                &quot;    moves items from source to destination&quot;,
                &quot;  Given [] and [banana, cherry]&quot;,
                &quot;    moves items from source to destination&quot;,
                &quot;  Given [apple] and [banana, cherry]&quot;,
                &quot;    moves items from source to destination&quot;
            )
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is of course overkill for our little example, but the ability to compose tests, contexts and fixtures allows us to reuse them all in creative ways. Let’s generalise our previous example to any mutable collection&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Fixture(
    val source: MutableCollection&amp;lt;String&amp;gt;,
    val destination: MutableCollection&amp;lt;String&amp;gt;
)

fun ContextBuilder&amp;lt;Fixture&amp;gt;.supportsMoveTo(
    collectionOf: (List&amp;lt;String&amp;gt;) -&amp;gt; MutableCollection&amp;lt;String&amp;gt;
) {
    context(&quot;empty source&quot;) {
        //...
    }
    context(&quot;non-empty source&quot;) {
        fixture {
            Fixture(collectionOf(aNonEmptyList), collectionOf(emptyList()))
        }

        context(&quot;empty destination&quot;) {
            test(&quot;should contain just the source&quot;) {
                moveInto(source, destination)
                assertEquals(collectionOf(aNonEmptyList), destination)
            }
        }

        context(&quot;non-empty destination&quot;) {
            deriveFixture {
                parentFixture.copy(destination = collectionOf(aNonEmptyListToo))
            }

            test(&quot;should contain destination plus source&quot;) {
                moveInto(source, destination)
                assertEquals(collectionOf(aNonEmptyListToo + aNonEmptyList), destination)
            }
        }

        after {
            assertEquals(collectionOf(emptyList()), source)
        }
    }
}

/*-
We can use this contract to test with different `MutableCollection`s by a specifying the concrete factory `collectionOf`
-*/

class ArrayListTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        supportsMoveTo { content -&amp;gt; ArrayList(content) }
    }
}

class LinkedListTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        supportsMoveTo { content -&amp;gt; LinkedList(content) }
    }
}

class SetTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        supportsMoveTo { content -&amp;gt; LinkedHashSet(content) }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;other-features&quot;&gt;Other Features&lt;/h2&gt;

&lt;p&gt;Minutest users are still exploring ways to exploit this revised test model to make tests more expressive and comprehensive. Other features that become simple to implement include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://oneeyedmen.com/property-based-testing-with-minutest.html&quot;&gt;Property based testing&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Sharing fixtures between test runs&lt;/li&gt;
  &lt;li&gt;Immutable fixtures&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/dmcg/minutest/blob/master/docs/fixtures.md#changing-fixture-type&quot;&gt;Mapping from one fixture type to another&lt;/a&gt; to expand or contract the focus of tests.&lt;/li&gt;
  &lt;li&gt;Logging test execution&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://oneeyedmen.com/test-driven-to-specification-with-minutest-part1.html&quot;&gt;Refactoring&lt;/a&gt; - for example flat TDD tests to a Spec or property-based tests.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;other-implementations&quot;&gt;Other Implementations&lt;/h2&gt;

&lt;p&gt;Minutest is a Kotlin library that integrates with JUnit 5 (and experimentally JUnit 4) to run its tests and provide assertions. While some of the expressiveness in the test specification requires Kotlin language features, I believe that a similar model could be implemented in other languages. In fact a similar, albeit dynamically typed, fixture model is available for &lt;a href=&quot;https://jasmine.github.io/2.8/introduction.html#section-The_%3Ccode%3Ethis%3C/code%3E_keyword&quot;&gt;Jasmine&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;By giving the fixture its own type, the problems of fixture lifecycle and reuse inherent in the Spec model can be mitigated. A framework such as Minutest that embraces this approach can reap further rewards in test expression, productivity and flexibility.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Property Based Testing With Minutest</title>
   <link href="http://0.0.0.0:4000/property-based-testing-with-minutest.html"/>
   <updated>2019-02-22T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/property-based-testing-with-minutest</id>
   <content type="html">&lt;p&gt;This is the bonus episode of a mini-series on my new test library, &lt;a href=&quot;https://github.com/dmcg/minutest&quot;&gt;Minutest&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;test-driven-to-specification-with-minutest-part1.html&quot;&gt;Part 1&lt;/a&gt; we looked at the Test Driven Development of an
extension function, &lt;code&gt;partition&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;test-driven-to-specification-with-minutest-part2.html&quot;&gt;Part 2&lt;/a&gt; we refactored the code into a
&lt;a href=&quot;http://rspec.info/&quot;&gt;Spec&lt;/a&gt; -style, with nested contexts giving a more formal specification of what the code does.&lt;/p&gt;

&lt;p&gt;In this part I’ll look at a different style of testing with Minutest -
&lt;a href=&quot;https://hypothesis.works/articles/what-is-property-based-testing/&quot;&gt;Property Based Testing&lt;/a&gt;. Instead of constructing
example inputs and testing against expected outcomes, Property Based Testing throws many inputs at a system and checks
the outcomes against a set of properties that we can say should hold true independent of the exact input.&lt;/p&gt;

&lt;h2 id=&quot;the-code-under-test&quot;&gt;The Code Under Test&lt;/h2&gt;

&lt;p&gt;Let’s remind ourselves of the code we’re testing.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;/**
 * Partitions the receiver into lists which contain the items that match the input corresponding predicate.
 *
 * If multiple predicates match an item, the item is attributed to the first which matches.
 */
fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;((T) -&amp;gt; Boolean)?, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return predicates.map { grouped.getOrDefault(it, emptyList()) }
}

private fun &amp;lt;T&amp;gt; Iterable&amp;lt;(T) -&amp;gt; Boolean&amp;gt;.firstMatch(item: T): ((T) -&amp;gt; Boolean)? =
    this.find { predicate -&amp;gt; predicate(item) }
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;what-are-our-properties&quot;&gt;What Are Our Properties?&lt;/h2&gt;

&lt;p&gt;The key to Property Based Testing is to find properties of outcomes that are true no matter what the input. For example,
the length of the output list will be the same as the length of the predicates, no matter what predicates are provided.
What other properties can you think of?&lt;/p&gt;

&lt;p&gt;Yes, it isn’t easy.&lt;/p&gt;

&lt;p&gt;Let’s park that for a while while we implement a bit of mechanism.&lt;/p&gt;

&lt;h2 id=&quot;unrolled-tests&quot;&gt;Unrolled Tests&lt;/h2&gt;

&lt;p&gt;What we want to do is run the same tests for a set
of input values. We’ll represent the inputs with a Fixture data class and write the following.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionPropertyTests : JUnit5Minutests {
    data class Fixture(
        val items: List&amp;lt;Int&amp;gt;,
        val predicates: List&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;
    )

    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        context(&quot;empty predicates&quot;) {
            fixture { Fixture(emptyList(), emptyList()) }
            test(&quot;result size equals predicates size&quot;) {
                assertEquals(predicates.size, items.partition(predicates).size)
            }
            test(&quot;something else that should be true for any fixure&quot;) {}
        }
        context(&quot;some predicates&quot;) {
            fixture { Fixture(emptyList(), listOf(::isNegative, ::isZero, ::isPositive)) }
            test(&quot;result size equals predicates size&quot;) {
                assertEquals(predicates.size, items.partition(predicates).size)
            }
            test(&quot;something else that should be true for any fixture&quot;) {}
        }
        // we could go on
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;building-contexts-in-code&quot;&gt;Building Contexts In Code&lt;/h2&gt;

&lt;p&gt;Now obviously this doesn’t scale. Luckily Minutest is &lt;em&gt;All Just Kotlin™&lt;/em&gt; so we can build those contexts in code.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val fixtures = listOf(
    Fixture(emptyList(), emptyList()),
    Fixture(emptyList(), listOf(::isNegative, ::isZero, ::isPositive))
)

fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
    fixtures.forEach { fixture -&amp;gt;
        context(&quot;Inputs $fixture&quot;) {
            fixture { fixture }
            test(&quot;result size equals predicates size&quot;) {
                assertEquals(predicates.size, items.partition(predicates).size)
            }
            test(&quot;something else that should be true for any fixture&quot;) {}
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;scale-out-and-down&quot;&gt;Scale Out and Down&lt;/h2&gt;

&lt;p&gt;You can probably see where this is going - all we have to do is flesh-out the set of fixtures and tests.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Fixture(
    val items: List&amp;lt;Int&amp;gt;,
    val predicates: List&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;
) {
    fun result() = items.partition(predicates)
}

fun fixtures() = combinationsOf(
    listOf(
        emptyList(),
        listOf(1),
        listOf(-1, 0, 1, 2, 3),
        listOf(3, 2, 1, 0, -1),
        listOf(-1, -1, 0, 0, 1, 2, 3)
    ),
    listOf(
        emptyList(),
        listOf(::isZero),
        listOf(::isNegative, ::isZero, ::isPositive),
        //...
        listOf(::isPositive, ::isBiggerThan10)
    )
).map { (items, predicates) -&amp;gt; Fixture(items, predicates) }

fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
    fixtures().forEach { fixture -&amp;gt;
        context(&quot;Inputs $fixture&quot;) {
            fixture { fixture }
            test(&quot;result size equals predicates size&quot;) {
                assertEquals(predicates.size, result().size)
            }
            test(&quot;first output has every item in input that matches first predicate&quot;) {
                if (predicates.isNotEmpty()) {
                    assertEquals(items.filter { predicates[0](it) }, result()[0])
                }
            }
            test(&quot;no item in output doesn't match the corresponding predicate&quot;) {
                predicates.zip(result()).forEach { (predicate, resultForPredicate) -&amp;gt;
                    assertTrue(resultForPredicate.filterNot(predicate).isEmpty())
                }
            }
            test(&quot;every output item is in the input&quot;) {
                val outputs = result().flatten().toSet()
                assertTrue((outputs - items).isEmpty())
            }
            // ...
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I’m not an experienced Property Based Tester - I’m still finding my feet when it comes to finding good inputs and
properties that are minimal and expressive - but I do know that every time I thought of a new property, or came up with an
interesting new list of items or predicates, my confidence in the implementation increased. The testing was
exploratory, but with the advantages of automation and combinatorial growth. Not only that, but each new case increased
my confidence that any changes to the behaviour caused by refactoring would be caught by one of the hundreds of tests
generated this way.&lt;/p&gt;

&lt;h2 id=&quot;generating-inputs&quot;&gt;Generating Inputs&lt;/h2&gt;

&lt;p&gt;There are other ways of generating the inputs for Property Based Testing. One would be to generate random lists of items and
predicates rather than combinations of given ones. Another would be to start with some givens and mutate them, either
consistently or randomly. Both would give more confidence that we hadn’t rigged the input, at the expense of having to
manage the randomness.&lt;/p&gt;

&lt;p&gt;It’s also worth noting that if we generate many more tests we may come across limitations in our test reporting tools.
I &lt;em&gt;think&lt;/em&gt; that you could use Minutest to generate only one outer context and one inner test in these circumstances, but
collect any failures from all fixtures into a single result per test. I’ll write another post if I can.&lt;/p&gt;

&lt;h2 id=&quot;putting-it-all-together&quot;&gt;Putting It All Together&lt;/h2&gt;

&lt;p&gt;You are not alone if you couldn’t read these tests and predict what the &lt;code&gt;partition&lt;/code&gt; method actually did. Maybe I’m just not
good enough at specifying the properties - or maybe we do need human-centred examples in that role. Luckily there is
nothing to stop us having the examples for humans and the property based tests for regression. We can merge the specification
tests from last time with these, and run them both with Minutest - they can even share the same Fixture.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {

    data class Fixture(
        val items: List&amp;lt;Int&amp;gt; = emptyList(),
        val predicates: List&amp;lt;(Int) -&amp;gt; Boolean&amp;gt; = emptyList()
    ) {
        fun result() = items.partition(predicates)

        fun assertResultIs(vararg expected: List&amp;lt;Int&amp;gt;) {
            assertEquals(expected.asList(), result())
        }
    }

    fun specs() = rootContext&amp;lt;Fixture&amp;gt; {
        fixture { Fixture() }

        context(&quot;some items&quot;) {
            withItems(-1, 0, 1, 2, 3)
            context(&quot;no predicates&quot;) {
                test(&quot;returns empty list&quot;) {
                    assertResultIs()
                }
            }
            context(&quot;everything matches something&quot;) {
                withPredicates(::isNegative, ::isZero, ::isPositive)
                test(&quot;returns a list for each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;a predicate doesn't match any item&quot;) {
                withPredicates(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive)
                test(&quot;returns an empty list for that predicate&quot;) {
                    assertResultIs(emptyList(), listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;an item doesn't match any predicate&quot;) {
                withPredicates(::isNegative, ::isPositive)
                test(&quot;item is not in the returned lists&quot;) {
                    assertResultIs(listOf(-1), listOf(1, 2, 3))
                }
            }
            context(&quot;an item matches more than one predicate&quot;) {
                withPredicates(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive, ::isBiggerThan1)
                test(&quot;item is assigned to the first matching predicate&quot;) {
                    assertResultIs(emptyList(), listOf(-1), listOf(0), listOf(1, 2, 3), emptyList())
                }
            }
            context(&quot;repeated predicates&quot;) {
                withPredicates(::isNegative, ::isNegative, ::isZero, ::isPositive)
                test(&quot;item is assigned to each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;lambda predicates&quot;) {
                withPredicates({ x -&amp;gt; isNegative(x) }, { x -&amp;gt; isPositive(x) })
                test(&quot;item is assigned to each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(1, 2, 3))
                }
            }
            context(&quot;items in a different order&quot;) {
                withItems(3, 2, 1, 0, -1)
                withPredicates(::isNegative, ::isZero, ::isPositive)
                test(&quot;input order is preserved&quot;) {
                    assertResultIs(listOf(-1), listOf(0), listOf(3, 2, 1))
                }
            }
        }
        context(&quot;no items&quot;) {
            context(&quot;no predicates&quot;) {
                test(&quot;returns empty list&quot;) {
                    assertResultIs()
                }
            }
            context(&quot;some predicates&quot;) {
                withPredicates(::isNegative, ::isZero, ::isPositive)
                test(&quot;returns an empty list for each predicate&quot;) {
                    assertResultIs(emptyList(), emptyList(), emptyList())
                }
            }
        }
    }

    private fun fixtures() = combinationsOf(
        listOf(
            emptyList(),
            listOf(1),
            listOf(-1, 0, 1, 2, 3),
            listOf(3, 2, 1, 0, -1),
            listOf(-1, -1, 0, 0, 1, 2, 3)
        ),
        listOf(
            emptyList(),
            listOf(::isZero),
            listOf(::isNegative, ::isZero, ::isPositive),
            listOf(::isPositive, ::isZero, ::isNegative),
            listOf(::isZero, ::isZero, ::isPositive),
            listOf(::isZero, ::isZero, ::isPositive, ::isPositive),
            listOf(::isPositive, ::isBiggerThan1),
            listOf(::isPositive, ::isBiggerThan10)
        )
    ).map { (items, predicates) -&amp;gt; Fixture(items, predicates) }

    fun properties() = rootContext&amp;lt;Fixture&amp;gt; {
        fixtures().forEach { fixture -&amp;gt;
            context(&quot;Inputs $fixture&quot;) {
                fixture { fixture }
                test(&quot;result size equals predicates size&quot;) {
                    assertEquals(predicates.size, result().size)
                }
                test(&quot;first output has every item in input that matches first predicate&quot;) {
                    if (predicates.isNotEmpty()) {
                        assertEquals(items.filter { predicates[0](it) }, result()[0])
                    }
                }
                test(&quot;no item in output doesn't match the corresponding predicate&quot;) {
                    predicates.zip(result()).forEach { (predicate, resultForPredicate) -&amp;gt;
                        assertTrue(resultForPredicate.filterNot(predicate).isEmpty())
                    }
                }
                test(&quot;every output item is in the input&quot;) {
                    assertTrue((result().flatten().toSet() - items).isEmpty())
                }
                test(&quot;the order of items in each output is the same as the order in the input&quot;) {
                    result().forEach { listInResult -&amp;gt;
                        val correspondingInputItems = items.filter { listInResult.contains(it) }
                        assertEquals(correspondingInputItems, listInResult)
                    }
                }
                test(&quot;no item is in more than one output&quot;) {
                    // Outputs for the same predicate are considered the same output
                    result().forEach { listInResult -&amp;gt;
                        val otherItems = result().filterNot { it == listInResult }.flatten()
                        assertEquals(listInResult - otherItems, listInResult)
                    }
                }
                test(&quot;identical predicates result in the same output&quot;) {
                    val resultsBySamePredicate: Map&amp;lt;(Int) -&amp;gt; Boolean, List&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;&amp;gt; =
                        predicates.zip(result()).groupBy(
                            { (predicate, _) -&amp;gt; predicate }, { (_, resultForPredicate) -&amp;gt; resultForPredicate }
                        ).filterValues { it.size &amp;gt; 1 }
                    resultsBySamePredicate.values.forEach { resultForPredicate -&amp;gt;
                        assertTrue(resultForPredicate.size &amp;gt; 1)
                        assertTrue(resultForPredicate.itemsAreTheSame())
                    }
                }
            }
        }
    }
    private fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.itemsAreTheSame() = this.toSet().size == 1

    private fun TestContextBuilder&amp;lt;Fixture, Fixture&amp;gt;.withItems(vararg items: Int) =
        before_ { copy(items = items.asList()) }

    private fun TestContextBuilder&amp;lt;Fixture, Fixture&amp;gt;.withPredicates(vararg predicates: (Int) -&amp;gt; Boolean) =
        before_ { copy(predicates = predicates.asList()) }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Property Based Tests allow us to specify the behaviour of code in a very different way to the usual examples or
specifications. They can allow easy working of edge-cases, increase our rigour and give increased robustness against
regressions, but may not communicate well with the users of our code. Combining specifications and property based tests
looks promising, especially where the tests can share infrastructure and setup.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Test Driven to Specification with Minutest - Part 2</title>
   <link href="http://0.0.0.0:4000/test-driven-to-specification-with-minutest-part2.html"/>
   <updated>2019-02-17T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/test-driven-to-specification-with-minutest-part2</id>
   <content type="html">&lt;p&gt;This is the second part of a mini-series on &lt;a href=&quot;https://github.com/dmcg/minutest&quot;&gt;Minutest&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;test-driven-to-specification-with-minutest-part1.html&quot;&gt;Part 1&lt;/a&gt; we looked at the Test Driven Development of an
extension function, &lt;code&gt;partition&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In this installment we’ll look at refactoring the (in many ways pretty arbitrary) tests that resulted into a more
formal specification of what our code does.&lt;/p&gt;

&lt;h2 id=&quot;the-code-under-test&quot;&gt;The Code Under Test&lt;/h2&gt;

&lt;p&gt;To remind ourselves - here is the code:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;((T) -&amp;gt; Boolean)?, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return predicates.map { grouped.getOrDefault(it, emptyList()) }
}

private fun &amp;lt;T&amp;gt; Iterable&amp;lt;(T) -&amp;gt; Boolean&amp;gt;.firstMatch(item: T): ((T) -&amp;gt; Boolean)? =
    this.find { predicate -&amp;gt; predicate(item) }
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;the-tdd-tests&quot;&gt;The TDD Tests&lt;/h2&gt;

&lt;p&gt;Here are the tests from the end of our TDD session.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
        test(&quot;every item matches a predicate and every predicate matches an item&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;an item matches no predicate&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = listOf(::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;a predicate matches no item&quot;) {
            val items = listOf(0, 1, 2, 3)
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(), listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;some items no predicates&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
            val result = items.partition(predicates)
            assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
        }
        test(&quot;some predicates no items&quot;) {
            val items = emptyList&amp;lt;Int&amp;gt;()
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(emptyList&amp;lt;Int&amp;gt;(), emptyList(), emptyList()), result)
        }
        test(&quot;no predicates no items&quot;) {
            val items = emptyList&amp;lt;Int&amp;gt;()
            val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
            val result = items.partition(predicates)
            assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Personally, even though we’ve tried to be formal in the names of our tests, I find that it’s hard to see the structure
in this flat list. Another problem is that the test names tell us the conditions - the ‘whens’, but don’t actually tell
us what the assertions mean. We can fix that with more words, but then we have a sea of text to deal with.&lt;/p&gt;

&lt;p&gt;Finally there is all that duplication.&lt;/p&gt;

&lt;h2 id=&quot;removing-duplication&quot;&gt;Removing Duplication&lt;/h2&gt;

&lt;p&gt;I guess that’s the easiest thing to address. Let’s extract a check function.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
    test(&quot;every item matches a predicate and every predicate matches an item&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        check(items, predicates, listOf(listOf(-1), listOf(0), listOf(1, 2, 3)))
    }
    test(&quot;an item matches no predicate&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = listOf(::isZero, ::isPositive)
        check(items, predicates, listOf(listOf(0), listOf(1, 2, 3)))
    }
    test(&quot;a predicate matches no item&quot;) {
        val items = listOf(0, 1, 2, 3)
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        check(items, predicates, listOf(listOf(), listOf(0), listOf(1, 2, 3)))
    }
    test(&quot;some items no predicates&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
        check(items, predicates, emptyList())
    }
    test(&quot;some predicates no items&quot;) {
        val items = emptyList&amp;lt;Int&amp;gt;()
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        check(items, predicates, listOf(emptyList(), emptyList(), emptyList()))
    }
    test(&quot;no predicates no items&quot;) {
        val items = emptyList&amp;lt;Int&amp;gt;()
        val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
        check(items, predicates, emptyList())
    }
}

private fun &amp;lt;T&amp;gt; check(items: List&amp;lt;T&amp;gt;, predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;, expected: List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt;) {
    assertEquals(expected, items.partition(predicates))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That’s a bit better, or at least a bit shorter. Actually our cognitive load looking at the tests is reduced, because
we can be reasonably sure that each is doing the same thing.&lt;/p&gt;

&lt;h2 id=&quot;grouping-into-contexts&quot;&gt;Grouping into Contexts&lt;/h2&gt;

&lt;p&gt;We’re still left with a flat list of 6 tests though. Minutest allows the grouping of tests into contexts - let’s try
just grouping what we have.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
    context(&quot;some items&quot;) {
        test(&quot;every item matches a predicate and every predicate matches an item&quot;) {
            // ...
        }
        test(&quot;an item matches no predicate&quot;) {
            // ...
        }
        test(&quot;a predicate matches no item&quot;) {
            // ...
        }
        test(&quot;no predicates&quot;) {
            // ...
        }
    }
    context(&quot;no items&quot;) {
        test(&quot;some predicates&quot;) {
            // ...
        }
        test(&quot;no predicates&quot;) {
            // ...
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This helps a bit, but there is no relationship in code between the context and its name. That would be a nice feature,
and Minutest supports this with fixtures. I think of the fixture as the world of the tests - all the state we need to
concern ourselves with.&lt;/p&gt;

&lt;h2 id=&quot;adding-a-fixture&quot;&gt;Adding a Fixture&lt;/h2&gt;

&lt;p&gt;At the moment the fixture type is &lt;code&gt;Unit&lt;/code&gt; - the one in &lt;code&gt;rootContext&amp;lt;Unit&amp;gt;&lt;/code&gt;. Let’s change that to be a class containing
the items that we want to test with. This seems overkill for now, but bear with me.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {

    class Fixture(val items: List&amp;lt;Int&amp;gt;)

    fun tests() = rootContext&amp;lt;Fixture&amp;gt;() {
        context(&quot;some items&quot;) {
            // ...
            test(&quot;ok&quot;) {}
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you run this you get a &lt;del&gt;nasty &lt;code&gt;ClassCastException&lt;/code&gt; which is a &lt;a href=&quot;https://github.com/dmcg/minutest/issues/24&quot;&gt;bad way&lt;/a&gt; of&lt;/del&gt;
&lt;code&gt;IllegalStateException: Fixture has not been set in context &quot;some items&quot;&lt;/code&gt;
telling you that you need to tell Minutest how to provide a fixture to the tests.&lt;/p&gt;

&lt;p&gt;We can do that with a &lt;code&gt;fixture&lt;/code&gt; block, which returns the fixture that should be used in tests in the context. So in &lt;code&gt;some items&lt;/code&gt;
we use &lt;code&gt;Fixture(listOf(-1, 0, 1, 2, 3))&lt;/code&gt;, and in &lt;code&gt;no items&lt;/code&gt;, &lt;code&gt;Fixture(emptyList())&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {

    class Fixture(val items: List&amp;lt;Int&amp;gt;)

    fun tests() = rootContext&amp;lt;Fixture&amp;gt;() {
        context(&quot;some items&quot;) {
            fixture {
                Fixture(listOf(-1, 0, 1, 2, 3))
            }
            test(&quot;every item matches a predicate and every predicate matches an item&quot;) {
                val predicates = listOf(::isNegative, ::isZero, ::isPositive)
                check(items, predicates, listOf(listOf(-1), listOf(0), listOf(1, 2, 3)))
            }
            test(&quot;an item matches no predicate&quot;) {
                val predicates = listOf(::isZero, ::isPositive)
                check(items, predicates, listOf(listOf(0), listOf(1, 2, 3)))
            }
            test(&quot;a predicate matches no item&quot;) {
                // Note that we have added a predicate to allow the same items as the other tests in this context
                val predicates = listOf(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive)
                check(items, predicates, listOf(listOf(), listOf(-1), listOf(0), listOf(1, 2, 3)))
            }
            test(&quot;no predicates&quot;) {
                val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
                check(items, predicates, emptyList())
            }
        }
        context(&quot;no items&quot;) {
            fixture {
                Fixture(emptyList())
            }
            test(&quot;some predicates&quot;) {
                val predicates = listOf(::isNegative, ::isZero, ::isPositive)
                check(items, predicates, listOf(emptyList(), emptyList(), emptyList()))
            }
            test(&quot;no predicates&quot;) {
                val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
                check(items, predicates, emptyList())
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The reason that this compiles is that inside a &lt;code&gt;test&lt;/code&gt; block, &lt;code&gt;this&lt;/code&gt; is the fixture that was created, so that &lt;code&gt;items&lt;/code&gt;
now refers to &lt;code&gt;Fixture.items&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now we can do the same with predicates, introducing a context for the different values.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {

    data class Fixture(val items: List&amp;lt;Int&amp;gt;, val predicates: List&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;)

    fun tests() = rootContext&amp;lt;Fixture&amp;gt;() {
        context(&quot;some items&quot;) {
            fixture {
                Fixture(listOf(-1, 0, 1, 2, 3), emptyList())
            }
            context(&quot;every item matches a predicate and every predicate matches an item&quot;) {
                deriveFixture {
                    // derive fixture allows us to take the parent fixture and return a derivation
                    parentFixture.copy(predicates = listOf(::isNegative, ::isZero, ::isPositive))
                }
                test(&quot;returns a list for each predicate&quot;) {
                    check(items, predicates, listOf(listOf(-1), listOf(0), listOf(1, 2, 3)))
                }
            }
            context(&quot;an item matches no predicate&quot;) {
                deriveFixture {
                    parentFixture.copy(predicates = listOf(::isZero, ::isPositive))
                }
                test(&quot;item is not in the returned lists&quot;) {
                    check(items, predicates, listOf(listOf(0), listOf(1, 2, 3)))
                }
            }
            context(&quot;a predicate matches no item&quot;) {
                deriveFixture {
                    parentFixture.copy(
                        predicates = listOf(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive)
                    )
                }
                test(&quot;returns an empty list for that predicate&quot;) {
                    check(items, predicates, listOf(emptyList(), listOf(-1), listOf(0), listOf(1, 2, 3)))
                }
            }
            context(&quot;no predicates&quot;) {
                test(&quot;returns empty list&quot;) {
                    check(items, predicates, emptyList())
                }
            }
        }
        context(&quot;no items&quot;) {
            //...
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see now that there is a direct relationship between the (nested) name of the context and the state of the fixture.
Not only that, but because the conditions are moved out into the contexts, the tests are free to describe just the
result - eg &lt;code&gt;item is not in the returned lists&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;removing-more-duplication&quot;&gt;Removing More Duplication&lt;/h2&gt;

&lt;p&gt;A little bit of refactoring gives the following.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {

    data class Fixture(
        val items: List&amp;lt;Int&amp;gt; = emptyList(),
        val predicates: List&amp;lt;(Int) -&amp;gt; Boolean&amp;gt; = emptyList()
    ) {
        fun assertResultIs(vararg expected: List&amp;lt;Int&amp;gt;) {
            assertEquals(expected.asList(), items.partition(predicates))
        }

        fun withPredicates(vararg predicates: (Int) -&amp;gt; Boolean) =
            copy(predicates = predicates.asList())
    }

    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        context(&quot;some items&quot;) {
            fixture {
                Fixture(items = listOf(-1, 0, 1, 2, 3))
            }
            context(&quot;everything matches something&quot;) {
                deriveFixture {
                    withPredicates(::isNegative, ::isZero, ::isPositive)
                }
                test(&quot;returns a list for each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;a predicate doesn't match any item&quot;) {
                deriveFixture {
                    withPredicates(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive)
                }
                test(&quot;returns an empty list for that predicate&quot;) {
                    assertResultIs(emptyList(), listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;an item doesn't match any predicate&quot;) {
                deriveFixture {
                    withPredicates(::isNegative, ::isPositive)
                }
                test(&quot;item is not in the returned lists&quot;) {
                    assertResultIs(listOf(-1), listOf(1, 2, 3))
                }
            }
            context(&quot;no predicates&quot;) {
                test(&quot;returns empty list&quot;) {
                    assertResultIs()
                }
            }
        }
        context(&quot;no items&quot;) {
            //...
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is longer than the original, but, for me at least, the contexts give my brain room to consider other cases, and
somewhere to put the tests that doesn’t overwhelm the reader.&lt;/p&gt;

&lt;h2 id=&quot;hiding-minutest&quot;&gt;Hiding Minutest&lt;/h2&gt;

&lt;p&gt;Nitpicking - I’m not happy with the deriveFixture calls there - they leak Minutest minutiae into our tests. Luckily this is
&lt;em&gt;All Just Kotlin™&lt;/em&gt; and so we can make better named operations to do the job for us. I’m going with &lt;code&gt;withItems&lt;/code&gt; and
&lt;code&gt;withPredicates&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now our spec reads in a way that we might even show to our customers (except, perhaps, for the term &lt;code&gt;predicates&lt;/code&gt;). We
even have the cognitive space to add tests that show what happens in some special cases.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {

    data class Fixture(
        val items: List&amp;lt;Int&amp;gt; = emptyList(),
        val predicates: List&amp;lt;(Int) -&amp;gt; Boolean&amp;gt; = emptyList()
    ) {
        fun assertResultIs(vararg expected: List&amp;lt;Int&amp;gt;) {
            assertEquals(expected.asList(), items.partition(predicates))
        }
    }

    fun tests() = rootContext&amp;lt;Fixture&amp;gt; {
        fixture { Fixture() }

        context(&quot;some items&quot;) {
            withItems(-1, 0, 1, 2, 3)
            context(&quot;no predicates&quot;) {
                test(&quot;returns empty list&quot;) {
                    assertResultIs()
                }
            }
            context(&quot;everything matches something&quot;) {
                withPredicates(::isNegative, ::isZero, ::isPositive)
                test(&quot;returns a list for each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;a predicate doesn't match any item&quot;) {
                withPredicates(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive)
                test(&quot;returns an empty list for that predicate&quot;) {
                    assertResultIs(emptyList(), listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;an item doesn't match any predicate&quot;) {
                withPredicates(::isNegative, ::isPositive)
                test(&quot;item is not in the returned lists&quot;) {
                    assertResultIs(listOf(-1), listOf(1, 2, 3))
                }
            }
            context(&quot;an item matches more than one predicate&quot;) {
                withPredicates(::isBiggerThan10, ::isNegative, ::isZero, ::isPositive, ::isBiggerThan1)
                test(&quot;item is assigned to the first matching predicate&quot;) {
                    assertResultIs(emptyList(), listOf(-1), listOf(0), listOf(1, 2, 3), emptyList())
                }
            }
            context(&quot;repeated predicates&quot;) {
                withPredicates(::isNegative, ::isNegative, ::isZero, ::isPositive)
                test(&quot;item is assigned to each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(-1), listOf(0), listOf(1, 2, 3))
                }
            }
            context(&quot;lambda predicates&quot;) {
                withPredicates({ x -&amp;gt; isNegative(x) }, { x -&amp;gt; isPositive(x) })
                test(&quot;item is assigned to each predicate&quot;) {
                    assertResultIs(listOf(-1), listOf(1, 2, 3))
                }
            }
            context(&quot;items in a different order&quot;) {
                withItems(3, 2, 1, 0, -1)
                withPredicates(::isNegative, ::isZero, ::isPositive)
                test(&quot;input order is preserved&quot;) {
                    assertResultIs(listOf(-1), listOf(0), listOf(3, 2, 1))
                }
            }
        }
        context(&quot;no items&quot;) {
            context(&quot;no predicates&quot;) {
                test(&quot;returns empty list&quot;) {
                    assertResultIs()
                }
            }
            context(&quot;some predicates&quot;) {
                withPredicates(::isNegative, ::isZero, ::isPositive)
                test(&quot;returns an empty list for each predicate&quot;) {
                    assertResultIs(emptyList(), emptyList(), emptyList())
                }
            }
        }
    }

    private fun TestContextBuilder&amp;lt;Fixture, Fixture&amp;gt;.withItems(vararg items: Int) =
        // before_ allows us to replace an existing fixture, and to have multiple calls
        before_ { copy(items = items.asList()) }

    private fun TestContextBuilder&amp;lt;Fixture, Fixture&amp;gt;.withPredicates(vararg predicates: (Int) -&amp;gt; Boolean) =
        // so that we can combine withs in the same context
        before_ { copy(predicates = predicates.asList()) }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;I won’t claim that this is a particularly good specification for our partition - I’m just finding my way with this style
and find it hard to strike a balance between formality and comprehension. But I do know that had I tried to write a spec
before writing any code I would have floundered - this way we TDD’d our way to working code quickly, then produced a
more formal and comprehensive set of tests that capture more of the behaviour, with a good degree of rigour between the
contexts and the fixtures.&lt;/p&gt;

&lt;p&gt;If you liked this, please try the &lt;a href=&quot;property-based-testing-with-minutest&quot;&gt;bonus episode&lt;/a&gt; where I look at Property
Based Testing the same code using Minutest.&lt;/p&gt;

&lt;p&gt;[Post updated 2019-02-22]&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Test Driven to Specification with Minutest - Part 1</title>
   <link href="http://0.0.0.0:4000/test-driven-to-specification-with-minutest-part1.html"/>
   <updated>2019-02-16T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/test-driven-to-specification-with-minutest-part1</id>
   <content type="html">&lt;p&gt;This is the first in a mini-series on my new test library, &lt;a href=&quot;https://github.com/dmcg/minutest&quot;&gt;Minutest&lt;/a&gt;. I’ll post the
other installments over the next few days.&lt;/p&gt;

&lt;p&gt;Minutest allows the writing of tests in nested contexts, in a &lt;a href=&quot;http://rspec.info/&quot;&gt;Spec&lt;/a&gt;-style. But I find that, unless
the problem is very well, erm, specified, then specs are hard to write. In Test Driven Development we’re often exploring
the shape of a solution in a way that doesn’t fit well with specs, at least until we’re done.&lt;/p&gt;

&lt;p&gt;At the same time the tests that have helped us test drive functionality may not be ideal to communicate to future
developers what our code does, or to support safe refactoring of that code.&lt;/p&gt;

&lt;p&gt;The ideal situation then would be for our test framework to support us as we TDD our way to some code, and then refactor
the tests to a more formal specification. That is the subject of this series.&lt;/p&gt;

&lt;h2 id=&quot;the-problem&quot;&gt;The Problem&lt;/h2&gt;

&lt;p&gt;The functionality that I’m going to implement was inspired by a question on the
&lt;a href=&quot;https://kotlinlang.slack.com/archives/C0922A726/p1549403911046300&quot;&gt;Kotlin Slack&lt;/a&gt;. It boils down to partitioning a list
into other lists, rather like the standard &lt;code&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicate: (T) -&amp;gt; Boolean): Pair&amp;lt;List&amp;lt;T&amp;gt;, List&amp;lt;T&amp;gt;&amp;gt;&lt;/code&gt;
but for more than one predicate and more than two output lists.&lt;/p&gt;

&lt;h2 id=&quot;first-test&quot;&gt;First Test&lt;/h2&gt;

&lt;p&gt;This is TDD, so we had better start with a test. In Minutest it looks like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
        test(&quot;check I can run a test&quot;) {}
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can point to this in IntelliJ and run it - if all is well we are ready to get on with the job proper.&lt;/p&gt;

&lt;h2 id=&quot;driving-an-interface&quot;&gt;Driving an Interface&lt;/h2&gt;

&lt;p&gt;Now let’s sketch out the form of the function that we want to implement by creating an example.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
    test(&quot;explore the interface&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = listOf(
            Context2::isNegative,
            Context2::isZero,
            Context2::isPositive
        )
        val result = items.partition(predicates)
        assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code&gt;This won't compile until we add our predicates and a stub implementation.
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun isNegative(x: Int) = x &amp;lt; 0

fun isZero(x: Int) = x == 0
fun isPositive(x: Int) = x &amp;gt; 0

fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; = TODO()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now it compiles but fails with the &lt;code&gt;kotlin.NotImplementedError&lt;/code&gt; from our &lt;code&gt;TODO&lt;/code&gt;&lt;/p&gt;

&lt;h2 id=&quot;driving-an-implementation&quot;&gt;Driving an Implementation&lt;/h2&gt;

&lt;p&gt;I’m not clever enough to get this working in one step, so I’m going to step back and try just a degenerate case. We can
keep the first test but &lt;code&gt;SKIP&lt;/code&gt; it for now, and then add a test that I can get to pass.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
    SKIP - test(&quot;explore the interface&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        val result = items.partition(predicates)
        assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
    }
    test(&quot;no predicates&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
        val result = items.partition(predicates)
        assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This has the twin advantages of being a case that we are going to have to test for, and being easy to implement.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; = emptyList()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Woo-hoo, a passing test.&lt;/p&gt;

&lt;p&gt;OK, now lets add another easy test.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;test(&quot;predicates but no items&quot;) {
    val items = emptyList&amp;lt;Int&amp;gt;()
    val predicates = listOf(::isNegative, ::isZero, ::isPositive)
    val result = items.partition(predicates)
    assertEquals(listOf(emptyList&amp;lt;Int&amp;gt;(), emptyList(), emptyList()), result)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This fails because we need to return a list for each predicate - I can do that.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; =
    predicates.map { emptyList&amp;lt;T&amp;gt;() }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We now have two passing tests, and one skipped until I’m ready to step up. I suppose that had better be now. Reinstate the failing test and just go for it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
    test(&quot;items and predicates&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        val result = items.partition(predicates)
        assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
    }
    test(&quot;no predicates&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
        val result = items.partition(predicates)
        assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
    }
    test(&quot;predicates but no items&quot;) {
        val items = emptyList&amp;lt;Int&amp;gt;()
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        val result = items.partition(predicates)
        assertEquals(listOf(emptyList&amp;lt;Int&amp;gt;(), emptyList(), emptyList()), result)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My approach is to group the items by whether they match the predicate.&lt;/p&gt;

&lt;p&gt;Firstly I’ll add a function body buy some time,&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    return predicates.map { emptyList&amp;lt;T&amp;gt;() }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;then sketch out the intermediate.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;(T) -&amp;gt; Boolean, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return predicates.map { emptyList&amp;lt;T&amp;gt;() }
}

private fun &amp;lt;T&amp;gt; Iterable&amp;lt;(T) -&amp;gt; Boolean&amp;gt;.firstMatch(item: T): (T) -&amp;gt; Boolean = TODO()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now &lt;code&gt;firstMatch&lt;/code&gt; is just &lt;code&gt;find&lt;/code&gt;, except that returns a nullable. Hmmm, I suppose that is the case where there isn’t a
predicate to match an item. We can relax the type of the keys in our map to get it to compile&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;((T) -&amp;gt; Boolean)?, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return predicates.map { emptyList&amp;lt;T&amp;gt;() }
}

private fun &amp;lt;T&amp;gt; Iterable&amp;lt;(T) -&amp;gt; Boolean&amp;gt;.firstMatch(item: T): ((T) -&amp;gt; Boolean)? =
    this.find { predicate -&amp;gt; predicate(item) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There should be one value of &lt;code&gt;grouped&lt;/code&gt; for each of our predicates - so that this type-checks&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;((T) -&amp;gt; Boolean)?, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return grouped.values.toList()
}

&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;almost-there&quot;&gt;Almost There?&lt;/h2&gt;

&lt;p&gt;Running the tests, &lt;code&gt;items and predicates&lt;/code&gt; passes, so we did something right, but the other two fail, so they’ve proved
worthwhile too. &lt;code&gt;no predicates&lt;/code&gt; reports:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Expected :[]
Actual   :[[-1, 0, 1, 2, 3]]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;while &lt;code&gt;predicates but no items&lt;/code&gt; says:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Expected :[[], [], []]
Actual   :[]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It’s time to actually think…&lt;/p&gt;

&lt;p&gt;…&lt;/p&gt;

&lt;p&gt;and come to the conclusion that in both these cases we’re not returning a list for each predicate. Previously we &lt;code&gt;map&lt;/code&gt;ped
over the predicates to create a list for each in the output.&lt;/p&gt;

&lt;p&gt;Let’s do that, fetching the predicate’s own entry from the groups, and noting that the null-safety prevents us from
just indexing and instead makes us take the right decision to return an empty list if there are no items matching
the predicate.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;((T) -&amp;gt; Boolean)?, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return predicates.map { grouped.getOrDefault(it, emptyList()) }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Triumph - our tests pass - let’s review.&lt;/p&gt;

&lt;h2 id=&quot;working-code&quot;&gt;Working Code&lt;/h2&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
        test(&quot;items and predicates&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;no predicates&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
            val result = items.partition(predicates)
            assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
        }
        test(&quot;predicates but no items&quot;) {
            val items = emptyList&amp;lt;Int&amp;gt;()
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(emptyList&amp;lt;Int&amp;gt;(), emptyList(), emptyList()), result)
        }
    }
}

fun &amp;lt;T&amp;gt; Iterable&amp;lt;T&amp;gt;.partition(predicates: List&amp;lt;(T) -&amp;gt; Boolean&amp;gt;): List&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; {
    val grouped: Map&amp;lt;((T) -&amp;gt; Boolean)?, List&amp;lt;T&amp;gt;&amp;gt; = this.groupBy { item -&amp;gt;
        predicates.firstMatch(item)
    }
    return predicates.map { grouped.getOrDefault(it, emptyList()) }
}

private fun &amp;lt;T&amp;gt; Iterable&amp;lt;(T) -&amp;gt; Boolean&amp;gt;.firstMatch(item: T): ((T) -&amp;gt; Boolean)? =
    this.find { predicate -&amp;gt; predicate(item) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now if this code was just part of a test, or maybe some throwaway script, I’d probably stop there. But otherwise there
are too many loose ends for me to feel comfortable that I know the way that the code would behave in different situations.
I like the implementation - it’s declarative and the types feel good, but you’d still have to puzzle out the edge cases;
 and if that’s the case, then any refactoring might change the behaviour. Which in something like &lt;code&gt;partition&lt;/code&gt; could have
ripple-effects through any dependent code.&lt;/p&gt;

&lt;h2 id=&quot;adding-more-tests&quot;&gt;Adding More Tests&lt;/h2&gt;

&lt;p&gt;Looking through our test names, we can see a lack of precision. If we fix that we can see that we are missing the case
of no items and no predicates. This is just the sort of edge case that could happen and return an unexpected value -
lets check it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
    test(&quot;items and predicates&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        val result = items.partition(predicates)
        assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
    }
    test(&quot;some items no predicates&quot;) {
        val items = listOf(-1, 0, 1, 2, 3)
        val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
        val result = items.partition(predicates)
        assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
    }
    test(&quot;some predicates no items&quot;) {
        val items = emptyList&amp;lt;Int&amp;gt;()
        val predicates = listOf(::isNegative, ::isZero, ::isPositive)
        val result = items.partition(predicates)
        assertEquals(listOf(emptyList&amp;lt;Int&amp;gt;(), emptyList(), emptyList()), result)
    }
    test(&quot;no predicates no items&quot;) {
        val items = emptyList&amp;lt;Int&amp;gt;()
        val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
        val result = items.partition(predicates)
        assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thankfully that passes, giving us some confidence that our algorithm is sound.&lt;/p&gt;

&lt;p&gt;Now what about items that slip through the predicate net? We can predict that they won’t be returned in any of the lists.
Is this the behaviour that we want?&lt;/p&gt;

&lt;p&gt;The alternative would be to return these items in another list at the end of the result, so that the result is one list
larger than the size of the predicates list. I dislike this because of the asymmetry, and because
(I predict but haven’t proved) if we want a catch-all we can simply pass in a last predicate that always returns &lt;code&gt;true&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally we already know that predicates that match no item are represented by an empty list in the output - but let’s
write a test to prove it so that our future selves don’t have to think it through.&lt;/p&gt;

&lt;h2 id=&quot;our-tdd-solution&quot;&gt;Our TDD Solution&lt;/h2&gt;

&lt;p&gt;Our final tests for today’s installment are:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class PartitionTests : JUnit5Minutests {
    fun tests() = rootContext&amp;lt;Unit&amp;gt;() {
        test(&quot;every item matches a predicate and every predicate matches an item&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(-1), listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;an item matches no predicate&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = listOf(::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;a predicate matches no item&quot;) {
            val items = listOf(0, 1, 2, 3)
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(listOf(), listOf(0), listOf(1, 2, 3)), result)
        }
        test(&quot;some items no predicates&quot;) {
            val items = listOf(-1, 0, 1, 2, 3)
            val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
            val result = items.partition(predicates)
            assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
        }
        test(&quot;some predicates no items&quot;) {
            val items = emptyList&amp;lt;Int&amp;gt;()
            val predicates = listOf(::isNegative, ::isZero, ::isPositive)
            val result = items.partition(predicates)
            assertEquals(listOf(emptyList&amp;lt;Int&amp;gt;(), emptyList(), emptyList()), result)
        }
        test(&quot;no predicates no items&quot;) {
            val items = emptyList&amp;lt;Int&amp;gt;()
            val predicates = emptyList&amp;lt;(Int) -&amp;gt; Boolean&amp;gt;()
            val result = items.partition(predicates)
            assertEquals(emptyList&amp;lt;List&amp;lt;Int&amp;gt;&amp;gt;(), result)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If I didn’t have a Part 2 I think that I’d probably remove some of duplication from this code before checking it in. But
it’s much like many of my TDD tests before Minutest - OK, probabably good enough, but lacking some rigour and expressiveness.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;test-driven-to-specification-with-minutest-part2.html&quot;&gt;Part 2&lt;/a&gt; we will look at refactoring this code to be more
spec-like. With luck it will be more expressive and less duplicated while covering more of the behaviour of our
implementation.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 5 - Embracing Either</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-5.html"/>
   <updated>2018-06-04T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-5</id>
   <content type="html">&lt;p&gt;This is Part 5 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this episode we’ll look at an case where the functional style has some definite benefits over using exceptions, and then go on to try to solve a problem that you will come across that is less easily finessed.&lt;/p&gt;

&lt;h2 id=&quot;encapsulating-failure&quot;&gt;Encapsulating failure&lt;/h2&gt;

&lt;p&gt;Let’s start this episode with the case where using the functional Either type has some real advantages over exceptions.&lt;/p&gt;

&lt;p&gt;Let’s say that I’m processing a potentially huge file, translating every line to a number that I want to sum.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader): Long =
    reader.lineSequence().map(Integer::parseInt).fold(0L, Long::plus)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(Ordinarily we could call &lt;code&gt;.sum()&lt;/code&gt; on the sequence, but that returns an Int which may overflow too quickly, so here I accumulate to a Long)&lt;/p&gt;

&lt;p&gt;We run this for 5 minutes before discovering that some lines are corrupt, so that parseInt throws, aborting the whole process. Sigh. An expedient approach is just to catch the exception, log in place, and substitute a 0.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader): Long =
    reader.lineSequence()
        .map {
            try {
                Integer.parseInt(it)
            } catch (e: Exception) {
                System.err.println(e.message)
                0
            }
        }
        .fold(0L, Long::plus)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I might be happy with that for a one-off solution, but this hard-codes our error handling and, as is sometimes the case with exceptions, hides the happy path which is the point of the algorithm.&lt;/p&gt;

&lt;p&gt;Remembering our functional definition of parseInt&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf { Integer.parseInt(s) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;we &lt;em&gt;could&lt;/em&gt; delay our gratification by creating a sequence of Either&amp;lt;Exception, Int&amp;gt;, and then fold over that.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader): Long {
    val ints: Sequence&amp;lt;Either&amp;lt;Exception, Int&amp;gt;&amp;gt; = reader.lineSequence().map(::parseInt)
    return ints.fold(0L) { acc, intResult -&amp;gt;
        intResult.fold(
            { exception -&amp;gt;
                System.err.println(exception.message)
                acc
            },
            { result -&amp;gt;
                acc + result
            }
        )
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmmm, I’m not sure that is much better, especially with those two nested folds that really don’t mean the same thing unless you close your eyes and imagine very hard. The least we can do is to de-nest them&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader): Long {
    val ints: Sequence&amp;lt;Int&amp;gt; = reader.lineSequence()
        .map(::parseInt)
        .map { intResult -&amp;gt;
            intResult.fold(
                { exception -&amp;gt;
                    System.err.println(exception.message);
                    0
                },
                { result -&amp;gt; result }
            )
        }
    return ints.fold(0L, Long::plus)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can make things better by writing a little extension to allow us to not use Either.fold when we just want to use the value&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;L, R&amp;gt; Either&amp;lt;L, R&amp;gt;.orElse(whenLeft: (L) -&amp;gt; R): R = when(this) {
    is Left -&amp;gt; whenLeft(this.l)
    is Right -&amp;gt; this.r
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;so now we have&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader): Long {
    val ints: Sequence&amp;lt;Int&amp;gt; = reader.lineSequence()
        .map(::parseInt)
        .map {
            it.orElse { exception -&amp;gt;
                System.err.println(exception.message)
                0
            }
        }
    return ints.fold(0L, Long::plus)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we can pull that idea up a level&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;L, R&amp;gt; Sequence&amp;lt;Either&amp;lt;L, R&amp;gt;&amp;gt;.eachOrElse(whenLeft: (L) -&amp;gt; R): Sequence&amp;lt;R&amp;gt; = this.map {
    it.orElse(whenLeft)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;leaving us with the the still-a-bit-ugly&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader): Long {
    val ints: Sequence&amp;lt;Either&amp;lt;Exception, Int&amp;gt;&amp;gt; = reader.lineSequence().map(::parseInt)
    return ints
        .eachOrElse { exception -&amp;gt;
            System.err.println(exception)
            0
        }
        .fold(0L, Long::plus)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now though we have at least successfully separated what to do in the case of an error from our fundamental flow, allowing us to move the responsibility to the caller&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader, onError: (Exception) -&amp;gt; Int): Long =
    reader.lineSequence()
        .map(::parseInt)
        .eachOrElse(onError)
        .fold(0L, Long::plus)

fun sumLines(reader: BufferedReader): Long =
    sumLines(reader) { exception -&amp;gt;
        System.err.println(exception)
        0
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is typical of the functional programming approach - push all the nastiness to the outside of the system, leaving nice pure referentially-transparent core algorithms. Now that we’ve had that inspiration, we could of course do the same thing with exception-based code&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader, onError: (Exception) -&amp;gt; Int): Long =
    reader.lineSequence()
        .map {
            try {
                Integer.parseInt(it)
            } catch (e: Exception) {
                onError(e)
            }
        }
        .fold(0L, Long::plus)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which of these implementations is better is open to debate. Pretty much every programmer will be able to read the try version and work out what it does after a while, and I think that it will be more efficient. When you’re used to the declarative style though the eachOrElse version reveals the intention without having to run your brain as a virtual machine. These days I’d probably go with eachOrElse until I needed the performance.&lt;/p&gt;

&lt;p&gt;Before we go on, eagle-eyed readers might spot a source of failure that I had missed. Did you?&lt;/p&gt;

&lt;p&gt;I’ll give you a couple of minutes.&lt;/p&gt;

&lt;p&gt;What I’d failed to spot is that, if this were Java, calls to any methods on a Reader would declare an IOException, and we’d be forced to consider that reading every line might fail. Here the flow of control is inverted, so that the line sequence pokes strings at our code, but even so, every time it does the file could have been deleted or the WiFi could have gone down. So map can still throw an IOException that we are not revealing by returning Either&amp;lt;Exception, Long&amp;gt;. Our function should be declared as&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun sumLines(reader: BufferedReader, onError: (Exception) -&amp;gt; Int): Either&amp;lt;Exception, Long&amp;gt; = resultOf {
    reader.lineSequence().map(::parseInt).eachOrElse(onError).fold(0L, Long::plus)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Frankly this has depressed me a bit. Even when I’m trying to demonstrate how an Either type can help with error handling in Kotlin, I mess it up. I suppose that we’re actually no worse off than Python or C# or almost any other language developers though - we do the best we can, sometimes we make mistakes, and when we find them we do our best to fix them.&lt;/p&gt;

&lt;h2 id=&quot;dealing-with-control-flow&quot;&gt;Dealing with Control Flow&lt;/h2&gt;

&lt;p&gt;If you try this functional style of error handling, sooner or later you’ll run into places where, well, things get icky. Let’s interpret three strings as ints and add them, the old-fashioned way, with exceptions&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun addAsInts(s1: String, s2: String, s3: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf {
    Integer.parseInt(s1) + Integer.parseInt(s2) + Integer.parseInt(s3)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now how about with our functional parseInt and map / flatMap?&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun addAsInts(s1: String, s2: String, s3: String): Either&amp;lt;Exception, Int&amp;gt; =
    parseInt(s1).flatMap { i1 -&amp;gt;
        parseInt(s2).flatMap { i2 -&amp;gt;
            parseInt(s3).map { i3 -&amp;gt;
                i1 + i2 + i3
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;“Really Duncan - that’s better than exceptions?” I hear you cry.&lt;/p&gt;

&lt;p&gt;No, I can’t say that it is; not with a straight face anyway. We can make things a bit better if we’re prepared to use our orElse and early returns&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun addAsInts(s1: String, s2: String, s3: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf {
    parseInt(s1).orElse { return Left(it) } +
        parseInt(s2).orElse { return Left(it) } +
        parseInt(s3).orElse { return Left(it) }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which in turn can be sweetened a bit with&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;L, R&amp;gt; Either&amp;lt;L, R&amp;gt;.onLeft(abortWith: (Left&amp;lt;L&amp;gt;) -&amp;gt; Nothing): R = when(this) {
    is Left -&amp;gt; abortWith(this)
    is Right -&amp;gt; this.r
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;to give us&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun addAsInts(s1: String, s2: String, s3: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf {
    parseInt(s1).onLeft { return it } +
        parseInt(s2).onLeft { return it } +
        parseInt(s3).onLeft { return it }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but frankly my functional programmer friends hate early returns (which also complicate referential transparency) as much as they hate exceptions, so this is frowned upon.&lt;/p&gt;

&lt;p&gt;What is required here is what Haskell calls &lt;a href=&quot;https://en.wikibooks.org/wiki/Haskell/do_notation&quot;&gt;do-notation&lt;/a&gt;, which is a way to sequence expressions only evaluating the next if the previous didn’t ‘fail’. This is of course the role of exceptions and/or early returns in other languages.&lt;/p&gt;

&lt;p&gt;Functional programmers value referential transparency so much that Scala programmers are resigned to using their &lt;a href=&quot;https://stackoverflow.com/questions/10441559/scala-equivalent-of-haskells-do-notation-yet-again&quot;&gt;&lt;code&gt;for-comprehensions&lt;/code&gt;&lt;/a&gt; to solve this problem, and &lt;a href=&quot;http://arrow-kt.io/docs/patterns/monad_comprehensions/&quot;&gt;Arrow&lt;/a&gt; bends Kotlin’s coroutines to the same end. With Arrow I could write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Try&amp;lt;Int&amp;gt; = Try {
    Integer.parseInt(s)
}

fun addAsInts(s1: String, s2: String, s3: String): Try&amp;lt;Int&amp;gt;  =
    Try.monad().binding {
        val i1: Int = parseInt(s1).bind()
        val i2: Int = parseInt(s2).bind()
        val i3: Int = parseInt(s3).bind()
        i1 + i2 + i3
    }.ev()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(or at least I could until they changed the API again :-(&lt;/p&gt;

&lt;p&gt;Personally I’d rather keep things on a level that I can understand, and maybe even implement myself. So I’d be inclined to define&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun &amp;lt;R&amp;gt; Either&amp;lt;Exception, R&amp;gt;.orThrow(): R = when(this) {
    is Left -&amp;gt; throw this.l
    is Right -&amp;gt; this.r
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and use it like this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun addAsInts(s1: String, s2: String, s3: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf {
    parseInt(s1).orThrow() +
        parseInt(s2).orThrow() +
        parseInt(s3).orThrow()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I’m really not enough of a functional programmer to argue that this is as functionally-pure as do-notation, but from the trenches where I stand I can’t see the difference. Combining exceptions with an Either type in this way at least plays to the strengths of the JVM in exception handling, but you may prefer Arrow, even if examining the bytecode it produces is enough to crash IntelliJ.&lt;/p&gt;

&lt;p&gt;I think that’s enough for today. In the next installment I hope to make some recommendations for how an API might document its failure modes in a manner that combines the best of checked exceptions and Either types.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 4 - Either v Exception</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-4.html"/>
   <updated>2018-04-21T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-4</id>
   <content type="html">&lt;p&gt;This is Part 4 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this fourth episode I’ll compare the pros and cons of using an Either type compared to Exceptions. This is hard-won information - there are plenty of functional programmers who will tell you the advantages of Either - I haven’t yet found one who will tell you the disadvantages.&lt;/p&gt;

&lt;p&gt;That said, from here on in you should know that I’m less sure of myself. There may be solutions to problems that I haven’t been exposed to, or better ways of achieving the same ends. Part of my motivation for writing this series is to get things straight in my head and to start a discussion, so please let me know when I’m wrong. The last post started an interesting &lt;a href=&quot;https://www.reddit.com/r/Kotlin/comments/8dmc5i/functional_error_handling_in_kotlin_part_3_result/&quot;&gt;discussion on Reddit&lt;/a&gt;. &lt;a href=&quot;https://www.reddit.com/r/Kotlin/comments/8ej18c/functional_error_handling_in_kotlin_part_4_either/&quot;&gt;Discuss this post&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, &lt;em&gt;I may be wrong&lt;/em&gt;, but I believe that even in Haskell, our goto source for FP patterns, Either does not replace exceptions. They can still be raised by those conditions that Java would signal with Errors or unchecked Exceptions - out of memory, integer divide by 0, out of bounds array access etc. So, referring back to &lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1&lt;/a&gt;, we should consider using Either only for those cases where checked exceptions would be appropriate, and returning null to signal a failure isn’t good enough.&lt;/p&gt;

&lt;p&gt;One easy-to-overlook feature of checked exceptions is that they obey laws of type-substitutability. So, as FileNotFoundException extends IOException, given&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;class FileInputStream {
    public FileInputStream(String name) throws FileNotFoundException {...}
    public int read() throws IOException {...}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I can invoke methods and pass on the common exception superclass&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public int readFirstByte(String filename) throw IOException {
    return FileInputStream(name).read(); // TODO - close stream
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We &lt;em&gt;can&lt;/em&gt; do the same thing with Either.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun openFile(name: String): Either&amp;lt;FileNotFoundException, InputStream&amp;gt; = TODO()

fun InputStream.eitherRead(): Either&amp;lt;IOException, Int&amp;gt; = TODO()

fun readFirstByte(filename: String): Either&amp;lt;IOException, Int&amp;gt; =
    openFile(filename).flatMap { it.use { it.eitherRead() } }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So the types work, now we just have to implement the functions.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Suppress(&quot;UNCHECKED_CAST&quot;)
fun openFile(name: String): Either&amp;lt;FileNotFoundException, InputStream&amp;gt; =
    resultOf {
        FileInputStream(name)
    } as Either&amp;lt;FileNotFoundException, InputStream&amp;gt;

@Suppress(&quot;UNCHECKED_CAST&quot;)
fun InputStream.eitherRead(): Either&amp;lt;IOException, Int&amp;gt; =
    resultOf {
        this.read()
    } as Either&amp;lt;IOException, Int&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmmm, those casts look mighty suspicious. If, say, &lt;code&gt;this.read()&lt;/code&gt; ended up throwing an IndexOutOfBoundsException, then the runtime has no way of knowing that the type of the result is wrong, which will potentially probably lead to really nasty debugging sessions. And while the signature of &lt;code&gt;this.read()&lt;/code&gt; is unlikely to change, if we were calling a more volatile API, it could add a type of thrown exception and our code would continue to compile but be subtly broken.&lt;/p&gt;

&lt;p&gt;I suppose I could change resultOf to check the type of exception seen is as expected&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;reified L, R&amp;gt; fastidiousResultOf(f: () -&amp;gt; R): Either&amp;lt;L, R&amp;gt; =
    try {
        Right(f())
    } catch (e: Exception) {
        if (e is L)
            Left(e)
        else
            throw e // or throw IllegalStateException(e)?
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but that seems asking for trouble unless everyone really internalises its behaviour. It all seems really complicated compared to those nice checked exceptions that everyone complained about, but maybe I was just used to making those work for me.&lt;/p&gt;

&lt;p&gt;Even if we dig ourselves deeper into our Exception type hole, Either can’t express another common checked exceptions idiom - a list of exceptions.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public int doSomething(String aParam) throws MyApiException, IOException { ... }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In practice therefore, when using Either the lowest actual subtype of the exception that may be returned does not seem to be specified in function signatures; Exception seems the norm -&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun openFile(name: String): Either&amp;lt;Exception, InputStream&amp;gt; =
    resultOf {
        FileInputStream(name)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is a shame, because despite all this functional cleverness we seem to be back to the de-facto situation of  - here is a function that can either succeed, or fail with pretty much any Throwable.&lt;/p&gt;

&lt;p&gt;Actually it isn’t quite that bleak. We’ve divided our error handling into&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Errors, which we probably can’t do anything about at any level, and are allowed to propagate as Throwables, and&lt;/li&gt;
  &lt;li&gt;Exceptions, that are returned in the Either, albeit with their actual type usually lost.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Furthermore, reviewing my current code-base’s use of Either for error handling, I find that we only return Either for functions that we reasonably &lt;em&gt;expect&lt;/em&gt; to fail for one of a few reasons&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The function is only defined for a subset of its inputs (partial functions like parseInt).&lt;/li&gt;
  &lt;li&gt;External systems don’t behave as we expect (usually expressed as IOException).&lt;/li&gt;
  &lt;li&gt;Some other condition not related to our inputs is is not met (eg timeouts).&lt;/li&gt;
  &lt;li&gt;The function calls another function that we expect to fail.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Our convention is that if a public function can reasonably expect to fail, it should return an Either, usually with Exception as the Left type. In practice then we have the equivalent of a single checked exception type (we don’t necessarily know what can go wrong, but we know that &lt;em&gt;something&lt;/em&gt; can) that plays nicely with higher-order functions such as List.map. If calling code needs to do different things with different failures then it is going to have to check the runtime type of Left, and if you want to know what types you need to check for you’re going to have to examine the whole expression tree, but this is what usually happens in practice even with checked exceptions - we handle a few predictable special cases and then see what else occurs in production.&lt;/p&gt;

&lt;p&gt;One situation that this convention doesn’t help with is functions that don’t return any result - things like &lt;code&gt;Writer.writeln(s: String)&lt;/code&gt;. In Java this throws IOException, which is checked, so you are forced to consider the failure. We could return Either&amp;lt;IOException, Unit&amp;gt; in these cases, but as the caller is not processing a return value, it is easy to ignore the error as well. Real functional programmers don’t have to worry about these cases, as functions called just for their side-effects will only be invoked in the context of special error handling (the IO Monad). This hasn’t actually come up in our real-world codebase so far so I don’t know what to advise - maybe throwing the exception is the least worst thing here.&lt;/p&gt;

&lt;p&gt;I think it may be time to the recap where we are with the whole exceptions v error results.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Early APIs returned error codes or set global error flags, but it was easy to forget to check these.&lt;/li&gt;
  &lt;li&gt;Exceptions were introduced to force explicit error handling, but it was still hard to know if a function could fail in practice.&lt;/li&gt;
  &lt;li&gt;Checked exceptions were introduced to make expected failure conditions more explicit.&lt;/li&gt;
  &lt;li&gt;Checked exceptions prove hard to reconcile with higher-order functions, go back 2 spaces.&lt;/li&gt;
  &lt;li&gt;Either types give many of the advantages of unchecked exceptions and knowing that a function can fail in practice, but only for functions where the caller is relying on using the result.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, you’re now asking, should I be using exceptions or Either in my code base?&lt;/p&gt;

&lt;p&gt;Well you won’t be fired for using exceptions. Just claim that you haven’t read these posts, point out that there is not a standard result type in the standard library, and continue business as usual. You can document, log and debug your way out of the problems that will occur in the same way as you always have. If you’d like to raise your game though, then I’d definitely experiment with the functional style. In my last two Kotlin projects we have used a specialised Result variant of Either, similar to the one presented here, as our default strategy, and I’d say that it has been easier to work with than the alternative exception free-for-all.&lt;/p&gt;

&lt;p&gt;If you’re a library writer and want to return Either from your functions, the lack of a functional error type in the standard library is going to cause you a problem. My advice would be to define a minimal Result type in your own package and return that - your clients can always write their own extension functions to convert to other representations.&lt;/p&gt;

&lt;p&gt;I think that I’m done for this episode. I’m aware that this series is a little disjointed and that the parts are individually too short. It’s a consequence I’m afraid of my working out what I think by writing, and needing to publish to get some feedback to inform future posts (&lt;a href=&quot;https://www.reddit.com/r/Kotlin/comments/8ej18c/functional_error_handling_in_kotlin_part_4_either/&quot;&gt;Discuss this post&lt;/a&gt;). Maybe I’ll be able to pull it all together into a single coherent article in the future. In the meantime, I think that there are two more posts to come - a review of existing Kotlin result types, and a post on making functional error handling work for you.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 3 - Result and Fold</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-3.html"/>
   <updated>2018-04-18T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-3</id>
   <content type="html">&lt;p&gt;This is Part 3 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this third episode I’ll look at some of the pros and cons of using an Either type for functional error handling.&lt;/p&gt;

&lt;p&gt;If you were ahead of the game in the last installment you’ll have noticed that we mostly caught exceptions and translated them to a Either.Left to signify failure.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Either&amp;lt;String, Int&amp;gt; = try {
    Right(Integer.parseInt(s))
} catch (exception: Exception) {
    Left(exception.message ?: &quot;No message&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may further have said to yourself that it seemed a shame to loose all that nice stack-tracey information that Java went out of it’s way to gather and use to create the exception. You may even have thought that we should have said&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Either&amp;lt;Exception, Int&amp;gt; = try {
    Right(Integer.parseInt(s))
} catch (exception: Exception) {
    Left(exception)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If so, I think you’re right. Let’s define a helper function to remove some of the boilerplate and refactor.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;R&amp;gt; resultOf(f: () -&amp;gt; R): Either&amp;lt;Exception, R&amp;gt; = try {
    Right(f())
} catch (e: Exception) {
    Left(e)
}

fun parseInt(s: String): Either&amp;lt;Exception, Int&amp;gt; = resultOf { Integer.parseInt(s) }

fun BufferedReader.eitherReadLine(): Either&amp;lt;Exception, String&amp;gt; = resultOf {
    this.readLine()
}

fun doubleString(s: String): Either&amp;lt;Exception, Int&amp;gt; = parseInt(s).map { 2 * it }

fun doubleNextLine(reader: BufferedReader): Either&amp;lt;Exception, Int&amp;gt; =
    reader.eitherReadLine().flatMap { doubleString(it) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Either&amp;lt;Exception, R&amp;gt; is such a common pattern that you may be tempted give it a special name. Arrow calls it &lt;a href=&quot;http://arrow-kt.io/docs/datatypes/try/&quot;&gt;Try&lt;/a&gt;. There are various other libraries that provide the abstraction as a Result type, including a &lt;a href=&quot;https://youtrack.jetbrains.com/issue/KT-18608&quot;&gt;proposal for the standard library&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are a couple of big problems though with making a concrete type that locks in Left to be Exception.&lt;/p&gt;

&lt;p&gt;The first problem is, should that be Exception, or Throwable? Arrow says Throwable, but I disagree. If we catch Throwable we are catching Errors, which &lt;code&gt;indicate serious problems that a reasonable application should not try to catch.&lt;/code&gt; In fact the Scala code on which the Arrow Try is based does not catch Error. The JetBrains Stdlib proposal catches all Throwables, but it is designed to represent the way that an expression terminated, rather than being used for functional error handling.&lt;/p&gt;

&lt;p&gt;The second big problem is that functions do not always fail with an exception. Especially if we’re just validating parameters in local functions it seems overkill to create an exception, quite an expensive operation, just to in order to represent a failure. So we’re probably going to want an Either&amp;lt;String, R&amp;gt; for these cases.&lt;/p&gt;

&lt;p&gt;A different way of formalising the use of Either as Result is offered by &lt;a href=&quot;https://github.com/npryce/result4k&quot;&gt;Result4K&lt;/a&gt;. This defines a sealed Result type with with Ok or Err subtypes, making the Right and Left cases clear. It’s my favourite of the solutions I’ve seen so far, but then it is from the home team.&lt;/p&gt;

&lt;p&gt;For now then, let’s stick with our generic Either type and see what more we can do with it.&lt;/p&gt;

&lt;p&gt;If there’s one thing that categorises functional programming with monads (no I don’t, but Either is) it’s delayed gratification. By mapping and flatmapping we don’t actually have to deal with errors at low levels - just pass their occurrence back to our callers. As with exceptions though, in the end someone will have to report failure.&lt;/p&gt;

&lt;p&gt;Back in &lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2&lt;/a&gt; we used &lt;code&gt;when&lt;/code&gt; to switch on the type of Either&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val result: Either&amp;lt;Exception, Int&amp;gt; = parseInt(readLine() ?: &quot;&quot;)
when (result) {
    is Right -&amp;gt; println(&quot;Your number was ${result.r}&quot;)
    is Left -&amp;gt; println(&quot;I couldn't read your number because ${result.l}&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The formalisation of this on Either is called &lt;code&gt;fold&lt;/code&gt;. It takes two functions and returns the result of calling the first if the Either is Left, the second if it is Right.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;L, R, T&amp;gt; Either&amp;lt;L, R&amp;gt;.fold(fl: (L) -&amp;gt; T, fr: (R) -&amp;gt; T): T =
    when (this) {
        is Right -&amp;gt; fr(this.r)
        is Left -&amp;gt; fl(this.l)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This lets us actually do something on the outside of our system&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;parseInt(readLine() ?: &quot;&quot;).fold(
    fr = { int -&amp;gt; println(&quot;Your number was $int&quot;) },
    fl = { exception -&amp;gt; println(&quot;I couldn't read your number because $exception&quot;) }
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again you have to squint quite hard to see the similarity between Either.fold and List.fold, but it turns out that functional programmers are so good at squinting that they have given it a special name - catamorphism.&lt;/p&gt;

&lt;p&gt;Personally I hate fold. Sure it unwraps the values for you, but putting lambdas inside a function invocation is ugly, and you pretty much always need to name the arguments because you want the success case first, but that doesn’t happen naturally when success is Right. I’ll often fall back on the raw &lt;code&gt;when&lt;/code&gt; formulation because it has the braces in the right place and reads naturally. I suppose the nastiness of fold at least encourages the user to only do it as a last resort, which is as it should be.&lt;/p&gt;

&lt;p&gt;Before we finish this episode, let’s just review what we have.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;sealed class Either&amp;lt;out L, out R&amp;gt;

data class Left&amp;lt;out L&amp;gt;(val l: L) : Either&amp;lt;L, Nothing&amp;gt;()

data class Right&amp;lt;out R&amp;gt;(val r: R) : Either&amp;lt;Nothing, R&amp;gt;()

inline fun &amp;lt;L, R1, R2&amp;gt; Either&amp;lt;L, R1&amp;gt;.map(f: (R1) -&amp;gt; R2): Either&amp;lt;L, R2&amp;gt; =
    when (this) {
        is Right -&amp;gt; Right(f(this.r))
        is Left -&amp;gt; this
    }

inline fun &amp;lt;L, R1, R2&amp;gt; Either&amp;lt;L, R1&amp;gt;.flatMap(f: (R1) -&amp;gt; Either&amp;lt;L, R2&amp;gt;): Either&amp;lt;L, R2&amp;gt; =
    when (this) {
        is Right -&amp;gt; f(this.r)
        is Left -&amp;gt; this
    }

inline fun &amp;lt;L, R, T&amp;gt; Either&amp;lt;L, R&amp;gt;.fold(fl: (L) -&amp;gt; T, fr: (R) -&amp;gt; T): T =
    when (this) {
        is Right -&amp;gt; fr(this.r)
        is Left -&amp;gt; fl(this.l)
    }

inline fun &amp;lt;R&amp;gt; resultOf(f: () -&amp;gt; R): Either&amp;lt;Exception, R&amp;gt; =
    try {
        Right(f())
    } catch (e: Exception) {
        Left(e)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There’s an awful lot of usefulness packed into a few lines of code there - a testament to Kotlin. The nice thing about using data classes and extension methods is that I don’t have to provide everything that you could want to do with Either as a method - you can add your own.&lt;/p&gt;

&lt;p&gt;If you’re beginning to experiment with functional error handling, I’d start with the definitions up above. If you find yourself doing something the same way more than twice, look to see if you add an extension method that expresses that operation. For example, I have&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;L, R, T&amp;gt; Either&amp;lt;L, R&amp;gt;.assertSuccess(f: (R) -&amp;gt; T) =
    when (this) {
        is Right -&amp;gt; f(this.r)
        is Left -&amp;gt; error(&quot;Value was not a Right, but a Left of ${this.l}&quot;)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which I use in test code in one of two ways&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val result: Either&amp;lt;Exception, String&amp;gt; = someOperation()

result.assertSuccess {
    assertEquals(&quot;banana&quot;, it)
}

val rightValue: String = result.assertSuccess { it }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once you’ve internalised some of the idioms, I’d then introduce a specific Result type, it can be it’s own sealed class or a typealias for Either. Or you can import someone else’s library and experiment with it.&lt;/p&gt;

&lt;p&gt;This series isn’t done yet. As you’ll find out if you do go down this path, there are plenty of pain points still to be addressed!&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 2 - Either</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-2.html"/>
   <updated>2018-04-18T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-2</id>
   <content type="html">&lt;p&gt;This is Part 2 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this second episode I’ll look at why functional programming tends to avoid exceptions, and what it uses instead.&lt;/p&gt;

&lt;p&gt;A distinguishing feature of functional programming is Referential Transparency. When this applies an expression may be transparently replaced by the result of its evaluation. So if I write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val secondsIn24hours = 60 * 60 * 24
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;then I can replace 60 * 60 with 3600 or 60 * 24 with 1440 without affecting the results, in fact the compiler may decide to replace the whole expression with 86400 for us. In contrast&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val dayLengthInHours = secondsIn(today()) / 60.0 / 60 / 24
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;is not referentially transparent, because today() will yield a different result than it did yesterday, and any day may have have a leap second applied.&lt;/p&gt;

&lt;p&gt;Some say that exceptions break referential transparency. I’m not convinced that it isn’t possible to unify the two, but I would accept that exceptions muddy the referential transparency waters. Why should we care? Because referential transparency makes it a lot easier to reason about the behaviour of a program, which in turn leads to fewer errors and more opportunities to refactor and optimise.&lt;/p&gt;

&lt;p&gt;If we want these things, then how should we signal and recover from errors? A time-honoured solution is to return a special value, often null. Let’s say that we want to parse a string into an integer. We could define&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Int? = TODO()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In Kotlin our clients would know that the result was &lt;code&gt;Int?&lt;/code&gt;, and would explicitly be forced to deal with the case where the string did not represent an int, so this would be a fine solution. In Java it would be less fine, as there is no way to make the client consider null. In this case we could (for Java 8+) define&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static Optional&amp;lt;Integer&amp;gt; parseInt(String s)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;where &lt;code&gt;Optional&amp;lt;T&amp;gt;&lt;/code&gt; has been provided for just this purpose of signalling nullability.&lt;/p&gt;

&lt;p&gt;Note that the standard Java function is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public static int parseInt(String s) throws NumberFormatException
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The problem here is that NumberFormatException is an unchecked exception, so that clients are not forced deal with it. Was that a good decision? I’d say in retrospect not in this case, but we’ll return to the problem of partial functions later.&lt;/p&gt;

&lt;p&gt;If we only care to know that something was amiss, and not the details, then a nullable or optional result is a good solution. But what if we want to convey where our parsing failed - what was the first character that wasn’t a digit? The NumberFormatException thrown by Java is able to carry that information (it doesn’t, but ho-hum). How can we replicate that behaviour in a functional way? In other words, how do we return either the error, or an integer?&lt;/p&gt;

&lt;p&gt;The answer, as they say, is in the question. We define a type Either, which can hold one of two types, but only one at a time.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;sealed class Either&amp;lt;out L, out R&amp;gt;

data class Left&amp;lt;out L&amp;gt;(val l: L) : Either&amp;lt;L, Nothing&amp;gt;()

data class Right&amp;lt;out R&amp;gt;(val r: R) : Either&amp;lt;Nothing, R&amp;gt;()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For no good reason that I can see, the convention is that Right is used for a result, Left for an error. If we stick to this convention we could define&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun parseInt(s: String): Either&amp;lt;String, Int&amp;gt; = try {
    Right(Integer.parseInt(s))
} catch (exception: Exception) {
    Left(exception.message ?: &quot;No message&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;How would we use this? As it is a sealed class, &lt;code&gt;when&lt;/code&gt; expressions and smart casting work really nicely to let us write things like&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val result: Either&amp;lt;String, Int&amp;gt; = parseInt(readLine() ?: &quot;&quot;)
when (result) {
    is Right -&amp;gt; println(&quot;Your number was ${result.r}&quot;)
    is Left -&amp;gt; println(&quot;I couldn't read your number because ${result.l}&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which admittedly is pathologically not functional, but gives the general idea. By returning an Either we force our clients to deal with the fact that we may have failed - in effect we have reproduced some of checked exceptions in a functional form. To embrace this style you make all your functions return Either and when they in turn invoke something that could fail, pass on any failure or unwrap the success and act on it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun doubleString(s: String): Either&amp;lt;String, Int&amp;gt; {
    val result: Either&amp;lt;String, Int&amp;gt; = parseInt(s)
    return when (result) {
        is Right -&amp;gt; Right(2 * result.r)
        is Left -&amp;gt; result
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Whilst using &lt;code&gt;when&lt;/code&gt; to unwrap an Either is cute, it quickly gets old, so we write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;L, R1, R2&amp;gt; Either&amp;lt;L, R1&amp;gt;.map(f: (R1) -&amp;gt; R2): Either&amp;lt;L, R2&amp;gt; =
    when (this) {
        is Right -&amp;gt; Right(f(this.r))
        is Left -&amp;gt; this
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which allows us to write the previous function as&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun doubleString(s: String): Either&amp;lt;String, Int&amp;gt; = parseInt(s).map { 2 * it }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Why is that function called &lt;code&gt;map&lt;/code&gt; and not &lt;code&gt;invokeUnlessLeft&lt;/code&gt;? Well if you squint you may be able to see that it is kind of the same thing as &lt;code&gt;List.map&lt;/code&gt;. Practice that squinting, because we are now going to define&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;L, R1, R2&amp;gt; Either&amp;lt;L, R1&amp;gt;.flatMap(f: (R1) -&amp;gt; Either&amp;lt;L, R2&amp;gt;): Either&amp;lt;L, R2&amp;gt; =
    when (this) {
        is Right -&amp;gt; f(this.r)
        is Left -&amp;gt; this
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This unpacks our value and uses it to invoke a function that in turn might fail (as it returns Either). What can we do with that? Well lets say we want to read from a Reader and print double the result.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun BufferedReader.eitherReadLine(): Either&amp;lt;String, String&amp;gt; =
    try {
        val line = this.readLine()
        if (line == null)
            Left(&quot;No more lines&quot;)
        else
            Right(line)
    } catch (x: IOException) {
        Left(x.message ?: &quot;No message&quot;)
    }


fun doubleNextLine(reader: BufferedReader): Either&amp;lt;String, Int&amp;gt; =
    reader.eitherReadLine().flatMap { doubleString(it) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code will return a Left with the failure if &lt;code&gt;eitherReadLine&lt;/code&gt; fails, otherwise it will return the result of &lt;code&gt;doubleString&lt;/code&gt;, which may itself be either a Left for failure or a Right with the final int result. In this way a chain of map and or flatMap calls acts like a series of expressions which might throw an exception - the first failure aborts the rest of the computation.&lt;/p&gt;

&lt;p&gt;Frankly, if you come from an OO background this style does take some getting used to. In my experience no amount of reading helps - you just have to knuckle down and start writing code this way until it becomes less painful. There are other helper functions that we can write to make it less verbose and perhaps easier to read and reason with, but the approach is still not without cost compared to just throwing and managing exceptions.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;next episode&lt;/a&gt; will look at more details of functional error handling and how to unify it with exceptions.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Failure is not an Option - Functional Error Handling in Kotlin. Part 1 - Exceptions</title>
   <link href="http://0.0.0.0:4000/failure-is-not-an-option-part-1.html"/>
   <updated>2018-04-17T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/failure-is-not-an-option-part-1</id>
   <content type="html">&lt;p&gt;This is Part 1 in a series looking at functional error handling in Kotlin. The parts are&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-1.html&quot;&gt;Part 1 - Exceptions&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;Part 2 - Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-3.html&quot;&gt;Part 3 - Result and Fold&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-4.html&quot;&gt;Part 4 - Either v Exception&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-5.html&quot;&gt;Part 5 - Embracing Either&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-6.html&quot;&gt;Part 6 - What Should You Do While Waiting for the Standard Result Type&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;failure-is-not-an-option-part-7.html&quot;&gt;Part 7 - Avoiding Failure&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this first post I’ll look at why Kotlin did not follow Java’s example and distinguish between checked and unchecked exceptions.&lt;/p&gt;

&lt;p&gt;Java has a simple and effective way of signalling and recovering from errors - exceptions. When the language was designed these were in fashion, for good reason - they are a simple and effective way of signalling and recovering from errors.&lt;/p&gt;

&lt;p&gt;Where Java went out on a limb was to introduce checked exceptions. Most languages treat exception types equally - code either succeeds and returns or fails and throws. Java distinguished between those conditions that you had to handle (checked exceptions) and those that you didn’t (all other exceptions, errors and throwables). Personally I like the scheme; but many didn’t, and for good reasons.&lt;/p&gt;

&lt;p&gt;Checked exceptions lead to a situation where the exceptions from lower level code would routinely be caught in order to rethrow them as another type to conform to the caller’s interface. Most other languages never bothered with this malarkey - unless intervening code was going to release resources, log or retry, exceptions generally propagated directly from the thrower to some top level generic handler that said, in essence, “Something went wrong somewhere.” In practice that was what most Java exception handling boiled down to as well, except that the report could now say that the you had a RuntimeException caused by a MyAPIException caused by a TheirAPIException caused by an ICustomerWcfServiceGetCustomerDetailBusinessFaultDetailFaultFaultMessage caused by an IOException. Sigh. Maybe the detractors had a point.&lt;/p&gt;

&lt;p&gt;One thing that isn’t in doubt is that the need to declare checked exceptions in method signatures made Java more verbose. More functional languages than Java have notation to describe a function type, so it is easy to see why the Kotlin language designers balked at &lt;code&gt;(URI, Int) -&amp;gt; Status throws IOException, YourAPIException&lt;/code&gt; and just decided to do away with the distinction between checked and unchecked exceptions. In practice when it came to its own functional abstractions - lambdas and streams - Java did the same thing. The functional interfaces invoked by stream methods don’t declare a checked exception; so you have to deal with any such issues inside your lambdas, even if all you do is convert to a runtime exception. This is for a good reason - if a lambda throws a checked exception, then anything that invokes the lambda can throw that exception, but now &lt;code&gt;Stream.map&lt;/code&gt; needs to be able to declare the throwing of the lambda’s exception somehow. (I think that this would have been possible in Java, at least for one exception per lambda, but it would lead to more complication than the already rococo generics could bear.)&lt;/p&gt;

&lt;p&gt;The de-facto position in Kotlin and (some of) Java 8 is therefore that errors are signified by raising an exception, and that code does not declare what exceptions it may raise. This leaves any code liable to failure in any way at any time, which in practice means that we revert to the situation in other languages with exceptions.&lt;/p&gt;

&lt;p&gt;So were checked exceptions just a bad idea? Well no. We’ve lost important information when we discard the concept - the way we expect code might fail, and how defensive we need to be about that. In practice it is usually far more likely that IO will fail than that our process will run out of memory - hence IOException is checked and OutOfMemoryError is not. When a Java method says &lt;code&gt;throws FileNotFoundException&lt;/code&gt; we can reason that if the user picked that file from a list it is probably still there and the exception is unlikely; if they typed-in a file name then the chances of it being right are about 10% and we’d better sit in a loop until it is. Either way we’re forced to think about the possibility and consider what to do locally, rather than abdicating responsibility to a generic handler after aborting the whole operation.&lt;/p&gt;

&lt;p&gt;In the &lt;a href=&quot;failure-is-not-an-option-part-2.html&quot;&gt;next part of this series&lt;/a&gt; I’ll look at why functional languages tend to avoid exceptions, and what they use instead.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Nothing? can save us</title>
   <link href="http://0.0.0.0:4000/nothing-can-save-us.html"/>
   <updated>2018-04-02T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/nothing-can-save-us</id>
   <content type="html">&lt;p&gt;Imagine, if you can, that you need to capture data about your Customers&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Customer(
    val id: String,
    val firstName: String,
    val lastName: String,
    val email: String,
    val addressLine1: String?,
    val addressLine2: String?,
    val addressLine3: String?,
    val postcode: String?,
    val iso2CountryCode: String,
    val phone: String?
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Due to the power of Kotlin null safety, we can see that we are required to capture a &lt;code&gt;firstName&lt;/code&gt;, &lt;code&gt;lastName&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt; and &lt;code&gt;iso2CountryCode&lt;/code&gt;, but that everything else is optional.&lt;/p&gt;

&lt;p&gt;We dutifully write an HTML form with validation rules to ensure that we have what we need, post it off to some HTTP handler, and set to to write the code to persist our data class to some datastore -&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;interface Customers {
    fun save(customer: Customer)
    fun findById(id: String): Customer?
    fun gdpr() = TODO(&quot;2018-05-25&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you’re ahead of me here, or just a run of the mill pedant, you’ll be saying, “But Duncan, what about that id?”&lt;/p&gt;

&lt;p&gt;Ah yes. Identifiers are usually dished out by the datastore, so we don’t have one at the point that we create a Customer to save. In Java null would be a valid value for the id (as well as every other reference), but if we specify the id as nullable in Kotlin; every time we reference a Customer id we will have to explicitly allow for the null - it’s going to get tedious pretty quickly.&lt;/p&gt;

&lt;p&gt;An alternative is to have a separate class to model the unsaved customer.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class UnsavedCustomer(
    val firstName: String,
    val lastName: String,
    val email: String,
    val addressLine1: String?,
    val addressLine2: String?,
    val addressLine3: String?,
    val postcode: String?,
    val iso2CountryCode: String,
    val phone: String?
)

interface Customers {
    fun save(customer: UnsavedCustomer): Customer
    fun findById(id: String): Customer
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That’s quite nice, because it shows that act of saving a customer is to turn an UnsavedCustomer into a (Saved)Customer. But the duplication between Customer and UnsavedCustomer is going to be a source of eternal shame.&lt;/p&gt;

&lt;h2 id=&quot;nothing-can-save-us&quot;&gt;Nothing? can save us&lt;/h2&gt;

&lt;p&gt;Let’s make the type of the id generic - constrained to &lt;code&gt;String?&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class CustomerData&amp;lt;out T : String?&amp;gt;(
    val id: T,
    val firstName: String,
    val lastName: String,
    val email: String,
    val addressLine1: String? = null,
    val addressLine2: String? = null,
    val addressLine3: String? = null,
    val postcode: String? = null,
    val iso2CountryCode: String,
    val phone: String? = null
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So our id must be compatible with nullable String.&lt;/p&gt;

&lt;p&gt;A saved Customer has an id, so we can tighten &lt;code&gt;String?&lt;/code&gt; to &lt;code&gt;String&lt;/code&gt; in this case.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;typealias Customer = CustomerData&amp;lt;String&amp;gt;

val existingCustomer = Customer(&quot;123&quot;, &quot;Fred&quot;, &quot;Flintstone&quot;, &quot;fred@bedrock.org&quot;, iso2CountryCode = &quot;US&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now a customer’s id must be non-null, which makes our life simple&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val thisIsFine: String = existingCustomer.id

val doesntCompile = Customer(null, &quot;Fred&quot;, &quot;Flintstone&quot;, &quot;fred@bedrock.org&quot;, iso2CountryCode = &quot;US&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We want our unsaved customers have a null id. The type of &lt;code&gt;null&lt;/code&gt; is &lt;code&gt;Nothing?&lt;/code&gt;, which is helpfully substitutable for &lt;code&gt;String?&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;typealias UnsavedCustomer = CustomerData&amp;lt;Nothing?&amp;gt;

val newCustomer = UnsavedCustomer(null, &quot;Fred&quot;, &quot;Flintstone&quot;, &quot;fred@bedrock.org&quot;, iso2CountryCode = &quot;US&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can’t use a String where you expect a Nothing? though, so null is the only acceptable value of an UnsavedCustomer id&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val typeMismatch = UnsavedCustomer(&quot;123&quot;, &quot;Fred&quot;, &quot;Flintstone&quot;, &quot;fred@bedrock.org&quot;, iso2CountryCode = &quot;US&quot;)
    // Required: Nothing? Found: String

val typeMismatch2: String = newCustomer.id
    // Required: String Found: Nothing?
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because of this you can’t use an UnsavedCustomer where you expected a saved one, or vice versa&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val typeMismatch3: Customer = newCustomer
val typeMismatch4: UnsavedCustomer = existingCustomer
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;although if you want to treat them alike you can define AnyCustomer&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;typealias AnyCustomer = CustomerData&amp;lt;*&amp;gt;

val ok: AnyCustomer = newCustomer
val okToo: AnyCustomer = existingCustomer

val AnyCustomer.isSaved get() = id != null
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To convert an Unsaved to a saved customer, supply the missing id&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Suppress(&quot;UNCHECKED_CAST&quot;)
fun UnsavedCustomer.saved(id: String) = (this as Customer).copy(id)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Full-disclosure - I thought this trick up a while ago, but we’ve only just put it into some production code, so I don’t know how it will turn out in practice. I’ll report back if there turn out to be any wrinkles that I haven’t spotted.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>KotlinConf</title>
   <link href="http://0.0.0.0:4000/kotlinconf.html"/>
   <updated>2017-11-04T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/kotlinconf</id>
   <content type="html">&lt;p&gt;My talk on the Cost of Kotlin Language Features at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; went pretty well I think.&lt;/p&gt;

&lt;p&gt;If you missed it, and don’t want to wait for it on Netflix, the slides (with speaker notes) are available on &lt;a href=&quot;https://docs.google.com/presentation/d/1wYX8RvspzQVxoGTlyagNqEyFGKIaTObSSz8CjoUpMks&quot;&gt;Google Slides&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The thing that impressed me most about the conference? I knew that JetBrains was a company of very clever people; I discovered that they are a company of very nice people. This was I believe their first big event, and they went about it with heart.&lt;/p&gt;

&lt;p&gt;Kudos JetBrains - you deserve success for Kotlin.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>The Cost of Kotlin Language Features - Preliminary Results Part 5 - Properties</title>
   <link href="http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part-5-properties.html"/>
   <updated>2017-10-28T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part-5-properties</id>
   <content type="html">&lt;p&gt;This is Part 5 in a series examining &lt;em&gt;The Cost of Kotlin Language Features&lt;/em&gt; in preparation for my presentation at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; in November. The series consists of&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;benchmarks.html&quot;&gt;Lessons Learned Writing Java and Kotlin Microbenchmarks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part1-baselines.html&quot;&gt;Part 1 - Baselines&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part2-strings.html&quot;&gt;Part 2 - Strings&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part3-invocation.html&quot;&gt;Part 3 - Invocation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-4-nullable-primitives.html&quot;&gt;Part 4 - Nullable Primitives&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-5-properties.html&quot;&gt;Part 5 - Properties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’m publishing these results ahead of KotlinConf to give an opportunity for peer-review, so please do give me your feedback about the content, experimental method, code and conclusions. If you’re reading this before November 2017 it isn’t too late to save me from making a fool of myself in person, rather than just on the Internet. As ever the current state of the code to run the benchmarks is available for inspection and comment &lt;a href=&quot;https://github.com/dmcg/kostings&quot;&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This post looks at the cost of Kotlin properties. Since my last post I’ve set up a Raspberry Pi booting to Bash to run the benchmarks - the result is a lot less noisy measurements and so better fidelity. &lt;a href=&quot;https://twitter.com/johnsnolan&quot;&gt;John Nolan&lt;/a&gt; continues to be the statistical brains behind the &lt;a href=&quot;https://github.com/npryce/hamkrest&quot;&gt;Hamkrest&lt;/a&gt; matchers used to show the relationships between results.&lt;/p&gt;

&lt;p&gt;For the first time these benchmarks use different &lt;code&gt;State&lt;/code&gt; objects between Java and Kotlin. In Java we have&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@State(Scope.Benchmark)
public class JavaState {

    public String field = &quot;hello&quot;;

    public String getField() {
        return field;
    }

    public String getConstant() {
        return &quot;hello&quot;;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;so that we can benchmark field access, getter access to that field, and calling a method that returns a constant.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Benchmark
public String field_access(JavaState state) {
   return state.field;
}

@Benchmark
public String getter(JavaState state) {
   return state.getField();
}

@Benchmark
public String method_access(JavaState state) {
   return state.getConstant();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Kotlin doesn’t allow direct access to a field, so the closest &lt;code&gt;State&lt;/code&gt; is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@State(Scope.Benchmark)
open class KotlinState {

    val fieldProperty = &quot;hello&quot;

    val methodProperty get() = &quot;hello&quot;

    fun getConstant() = &quot;hello&quot;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which we benchmark thus&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Benchmark
fun field_property(state: KotlinState): String {
    return state.fieldProperty
}

@Benchmark
fun method_property(state: KotlinState): String {
    return state.methodProperty
}

@Benchmark
fun constant_method(state: KotlinState): String {
    return state.getConstant()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here are the results for a typical test batch&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/properties-f1-w20-m500-run1.png&quot; alt=&quot;A Sample Properties Run&quot; /&gt;&lt;/p&gt;

&lt;p&gt;It looks like everything is the same speed except for &lt;code&gt;field_property&lt;/code&gt;. Let’s ask the stats on all the test results that I’ve collected so far.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;assertThat(JavaProperties::field_access, ! probablyDifferentTo(JavaProperties::getter))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This first assertion says that we can’t see any statistical difference between accessing the Java field directly, and calling the getter. That’s a surprise to me, as the former is a field access and the latter a method call and the same field access. I suppose that HotSpot has worked its magic (you may recall that we run these benchmarks many times and only start measuring after HotSpot has had time to do so) inlining the getter so that the running code is effectively the same.&lt;/p&gt;

&lt;p&gt;The second assertion&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;assertThat(JavaProperties::method_access,
    probablyFasterThan(JavaProperties::field_access, byMoreThan = 0.0002, butNotMoreThan = 0.0005))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;shows that calling a method that returns a constant is faster than accessing a field directly. Again that’s a little surprising, but the size of the effect is very small, between 0.02 - 0.05%.&lt;/p&gt;

&lt;p&gt;Accessing a Kotlin &lt;em&gt;method property&lt;/em&gt; (where we define a &lt;code&gt;get()&lt;/code&gt; operation for the property) is unsurprisingly indistinguishable from calling a method, as that is what it is.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;assertThat(KotlinProperties::method_property, ! probablyDifferentTo(KotlinProperties::constant_method))
assertThat(KotlinProperties::method_property, ! probablyDifferentTo(JavaProperties::method_access))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That just leaves the outlier - the standard Kotlin property with a backing field. This turns out to be statistically significantly faster than all the other access methods by between 1.5 and 2 %.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;assertThat(KotlinProperties::field_property, probablyFasterThan(JavaProperties::field_access,      byMoreThan = 0.015, butNotMoreThan = 0.02))
assertThat(KotlinProperties::field_property, probablyFasterThan(JavaProperties::getter,            byMoreThan = 0.015, butNotMoreThan = 0.02))
assertThat(KotlinProperties::field_property, probablyFasterThan(JavaProperties::method_access,     byMoreThan = 0.015, butNotMoreThan = 0.02))
assertThat(KotlinProperties::field_property, probablyFasterThan(KotlinProperties::method_property, byMoreThan = 0.015, butNotMoreThan = 0.02))
assertThat(KotlinProperties::field_property, probablyFasterThan(KotlinProperties::constant_method, byMoreThan = 0.015, butNotMoreThan = 0.02))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I really don’t understand this result. I’ve seen it visually in all the Raspberry Pi test runs and those assertions pass on the amalgam of over 5000 benchmark samples, so it isn’t a statistical aberration, but I can’t see how it can be.&lt;/p&gt;

&lt;p&gt;Looking at the bytecode, this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final field_property(LcostOfKotlin/properties/KotlinState;)Ljava/lang/String;
@Lorg/openjdk/jmh/annotations/Benchmark;()
@Lorg/jetbrains/annotations/NotNull;() // invisible
  @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
 L0
  ALOAD 1
  LDC &quot;state&quot;
  INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
 L1
  LINENUMBER 9 L1
  ALOAD 1
  INVOKEVIRTUAL costOfKotlin/properties/KotlinState.getFieldProperty ()Ljava/lang/String;
  ARETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;calling this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final getFieldProperty()Ljava/lang/String;
@Lorg/jetbrains/annotations/NotNull;() // invisible
 L0
  LINENUMBER 9 L0
  ALOAD 0
  GETFIELD costOfKotlin/properties/KotlinState.fieldProperty : Ljava/lang/String;
  ARETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;appears to be reliably executing faster than&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public field_access(LcostOfKotlin/properties/JavaState;)Ljava/lang/String;
@Lorg/openjdk/jmh/annotations/Benchmark;()
 L0
  LINENUMBER 9 L0
  ALOAD 1
  GETFIELD costOfKotlin/properties/JavaState.field : Ljava/lang/String;
  ARETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I can believe that HotSpot magic and speculative execution could boost the Kotlin property to the same speed as direct field access, but I don’t see how it can be reliably faster.&lt;/p&gt;

&lt;h1 id=&quot;addendum&quot;&gt;Addendum&lt;/h1&gt;

&lt;p&gt;Luckily the same John Nolan wondered if the &lt;code&gt;final&lt;/code&gt; modifiers could be significant. That led me to looking at the field definition, which in Kotlin is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;private final Ljava/lang/String; fieldProperty = &quot;hello&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That final probably allows HotSpot to more aggressively inline the value of the variable, safe in the knowledge that no-one can (should) change it. So it’s time to &lt;a href=&quot;https://www.youtube.com/watch?v=gmifaKiPa6M&quot;&gt;fire up the Raspi&lt;/a&gt; and run some more benchmarks to test this hypothesis.&lt;/p&gt;

&lt;h1 id=&quot;add-addendum&quot;&gt;Add-addendum&lt;/h1&gt;

&lt;p&gt;Well this is even more puzzling! I’ve added final field access Java benchmarks&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Benchmark
public String final_field_access(JavaState state) {
    return state.finalField;
}

@Benchmark
public String getter_of_final(JavaState state) {
    return state.getFinalField();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and a mutable Kotlin property benchmark&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Benchmark
fun mutable_property(state: KotlinState): String {
    return state.mutableProperty
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;img src=&quot;assets/properties-f1-w20-m500-run1a.png&quot; alt=&quot;A Revised Properties Run&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Against expectations, the Kotlin mutable property seems no slower than the immutable property, and the Java final field access is significantly slower than non-final field access.&lt;/p&gt;

&lt;p&gt;We get a clue why the Java final field is slower when we examine the bytecode.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final_field_access(LcostOfKotlin/properties/JavaState;)Ljava/lang/String;
  @Lorg/openjdk/jmh/annotations/Benchmark;()
   L0
    LINENUMBER 19 L0
    ALOAD 1
    INVOKEVIRTUAL java/lang/Object.getClass ()Ljava/lang/Class;
    POP
    LDC &quot;hello&quot;
    ARETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The value has been inlined, but only after a nugatory(?) call to get the class of the object that it came from. I really don’t understand this at all, but if you do, you could answer this &lt;a href=&quot;https://stackoverflow.com/q/46995632/97777&quot;&gt;Stack Overflow question&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;add-add-addendum&quot;&gt;Add-add-addendum&lt;/h1&gt;

&lt;p&gt;Well it &lt;a href=&quot;https://stackoverflow.com/a/46996143/97777&quot;&gt;turns out&lt;/a&gt; that the inlining of non-static final primitive and string fields is required by the Java Language Specification, and that &lt;code&gt;getClass&lt;/code&gt; call is a cheap null check to make sure that it can’t resolve if the referenced object is null. Given the confusion, and that, for me at least, this is the slower option, I’m not sure that was a good idea.&lt;/p&gt;

&lt;p&gt;And I still don’t know why the Kotlin property access is significantly faster than all other options. Let’s hope someone at KotlinConf can put me out of my misery.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>The Cost of Kotlin Language Features - Preliminary Results Part 4 - Nullable Primitives</title>
   <link href="http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part-4-nullable-primitives.html"/>
   <updated>2017-10-15T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part-4-nullable-primitives</id>
   <content type="html">&lt;p&gt;This is Part 4 in a series examining &lt;em&gt;The Cost of Kotlin Language Features&lt;/em&gt; in preparation for my presentation at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; in November. The series consists of&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;benchmarks.html&quot;&gt;Lessons Learned Writing Java and Kotlin Microbenchmarks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part1-baselines.html&quot;&gt;Part 1 - Baselines&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part2-strings.html&quot;&gt;Part 2 - Strings&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part3-invocation.html&quot;&gt;Part 3 - Invocation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-4-nullable-primitives.html&quot;&gt;Part 4 - Nullable Primitives&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-5-properties.html&quot;&gt;Part 5 - Properties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’m publishing these results ahead of KotlinConf to give an opportunity for peer-review, so please do give me your feedback about the content, experimental method, code and conclusions. If you’re reading this before November 2017 it isn’t too late to save me from making a fool of myself in person, rather than just on the Internet. As ever the current state of the code to run the benchmarks is available for inspection and comment &lt;a href=&quot;https://github.com/dmcg/kostings&quot;&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This post looks at the cost of nullability. My aim with this batch wasn’t to measure individual aspects of nullability so much as to simply model typical usage, so I picked adding to a nullable Int as an example.&lt;/p&gt;

&lt;p&gt;As usual we start with a baseline, consuming a constant expression passed in to the benchmark&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;open class KotlinPrimitives {

    @Benchmark
    fun _1_baseline(state: IntState, blackhole: Blackhole) {
        blackhole.consume(state._41)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And now a take that and add one to it&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Benchmark
    fun _2_sum(state: IntState, blackhole: Blackhole) {
        blackhole.consume(state._41 + 1)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Irritatingly, for the data that I have, that addition isn’t statistically detectable.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun `kotlin sum is not detectable`() {
        assertThat(this::_1_baseline, ! probablyDifferentTo(this::_2_sum))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Looking at the bytecode we see that the problem is that the code that we want to measure is swamped by code that we don’t want to measure, but has to be there to make the measurements possible.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;  public final _2_sum(LcostOfKotlin/primitives/IntState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 1
   L0
    ALOAD 1
    LDC &quot;state&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
    ALOAD 2
    LDC &quot;blackhole&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 22 L1
    ALOAD 2
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/primitives/IntState.get_41 ()I
    ICONST_1
    IADD
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (I)V
   L2
    LINENUMBER 23 L2
    RETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That &lt;code&gt;ICONST_1 IADD&lt;/code&gt; hidden in the middle is what we want to measure! Ah well. I could do better by not using the &lt;code&gt;Blackhole&lt;/code&gt;, and by arranging for field access to the &lt;code&gt;IntState._41&lt;/code&gt;, and switching off null-checks (ideally we’d have a way to do that for just this method with an annotation), but, well, I have a more detectable fish to fry.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Benchmark
    fun _3_sum_nullable(state: IntState, blackhole: Blackhole) {
        blackhole.consume(state.nullable_41!! + 1)
    }
    
    @Test
    fun `sum nullable is slower`() {
        assertThat(this::_2_sum, probablyFasterThan(this::_3_sum_nullable))
        assertThat(this::_2_sum, ! probablyFasterThan(this::_3_sum_nullable, byAFactorOf = 0.001))
    }    
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Adding a not-null !! assertion is statistically slower (when testing a value that is never null), but by less than 0.1%. In the bytecode we see the cost of the nullability&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    DUP
    IFNONNULL L2
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwNpe ()V
   L2
    INVOKEVIRTUAL java/lang/Integer.intValue ()I
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;is a check for &lt;code&gt;Integer != null&lt;/code&gt; and fetching the Int out of its box.&lt;/p&gt;

&lt;p&gt;What if we don’t know that Int can’t be null? We can use the Elvis operator to substitute 0 for null.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Benchmark
    fun _4_sum_always_null(state: IntState, blackhole: Blackhole) {
        blackhole.consume(state.nullInt ?: 0 + 1)
    }

    @Test
    fun `sum always null is slower`() {
        assertThat(this::_2_sum, probablyFasterThan(this::_4_sum_always_null))
        assertThat(this::_2_sum, ! probablyFasterThan(this::_4_sum_always_null, byAFactorOf = 0.001))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Uh huh - again, slower, but by less than 0.1% when our value is always null. Here’s the bytecode&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    DUP
    IFNULL L2
    INVOKEVIRTUAL java/lang/Integer.intValue ()I
    GOTO L3
   L2
    POP
    ICONST_1
   L3
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (I)V

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Argghh!&lt;/p&gt;

&lt;p&gt;Can you see the problem?&lt;/p&gt;

&lt;p&gt;It took me a while.&lt;/p&gt;

&lt;p&gt;We aren’t doing the addition at all any more. The Elvis operator has a lower precedence than addition. So the expression we’re measuring turns out to be&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    state.nullInt ?: (0 + 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the compiler is smart enough to know that &lt;code&gt;0 + 1 = 1&lt;/code&gt; for all values of 0 and 1, so it just substitutes &lt;code&gt;ICONST_1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Sigh.&lt;/p&gt;

&lt;p&gt;I’ll have to fix that an re-run the benchmarks (which takes several hours), but in the meantime, luckily, I already have some more results.&lt;/p&gt;

&lt;p&gt;For a long time I couldn’t detect any statistically significant different between the versions with and without null checks. I formed a hypothesis that, when the value being checked was always null or not null, &lt;a href=&quot;https://en.wikipedia.org/wiki/Branch_predictor&quot;&gt;branch prediction&lt;/a&gt; in either HotSpot or the processor was eating the cost of the check. So I measured with &lt;code&gt;Int?&lt;/code&gt;s that were randomly null or not&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Benchmark
    fun _5_sum_50_50_nullable(state: IntState, blackhole: Blackhole) {
        blackhole.consume(state.`50 50 NullableInt` ?: 0 + 1)
    }

    @Benchmark
    fun _6_sum_90_10_nullable(state: IntState, blackhole: Blackhole) {
        blackhole.consume(state.`90 10 NullableInt` ?: 0 + 1)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It turns out that branch prediction isn’t detectable&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun `branch_prediction is undetectable_50_50`() {
        assertThat(this::_4_sum_always_null, ! probablyDifferentTo(this::_5_sum_50_50_nullable))
    }

    @Test
    fun `branch_prediction is undetectable_90_10`() {
        assertThat(this::_4_sum_always_null, ! probablyDifferentTo(this::_6_sum_90_10_nullable))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but I suppose that &lt;a href=&quot;https://en.wikipedia.org/wiki/Speculative_execution&quot;&gt;Speculative Execution&lt;/a&gt; may play a part in the throughput of null checks.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>The Cost of Kotlin Language Features - Preliminary Results Part 3 - Invocation</title>
   <link href="http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part3-invocation.html"/>
   <updated>2017-10-14T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part3-invocation</id>
   <content type="html">&lt;p&gt;This is Part 3 in a series examining &lt;em&gt;The Cost of Kotlin Language Features&lt;/em&gt; in preparation for my presentation at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; in November. The series consists of&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;benchmarks.html&quot;&gt;Lessons Learned Writing Java and Kotlin Microbenchmarks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part1-baselines.html&quot;&gt;Part 1 - Baselines&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part2-strings.html&quot;&gt;Part 2 - Strings&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part3-invocation.html&quot;&gt;Part 3 - Invocation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-4-nullable-primitives.html&quot;&gt;Part 4 - Nullable Primitives&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-5-properties.html&quot;&gt;Part 5 - Properties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’m publishing these results ahead of KotlinConf to give an opportunity for peer-review, so please do give me your feedback about the content, experimental method, code and conclusions. If you’re reading this before November 2017 it isn’t too late to save me from making a fool of myself in person, rather than just on the Internet. As ever the current state of the code to run the benchmarks is available for inspection and comment &lt;a href=&quot;https://github.com/dmcg/kostings&quot;&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this post I look at the basic building block of functional programming - the first-class function. This allows us to treat a unit of computation as just another reference, to be passed around and then invoked when needed. I haven’t (yet?) compared the Kotlin performance to the equivalent Java - here I just compare different Kotlin code.&lt;/p&gt;

&lt;p&gt;The function we’re going to invoke is simple&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun aFunction(i: Int) = 2 * i
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and our baseline is invoking it directly.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;open class Invoking {

    @Benchmark
    fun baseline(intState: IntState) : Int {
        return aFunction(intState.randomInt)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;[In this case, I’m not consuming the result in a &lt;a href=&quot;http://openjdk.java.net/projects/code-tools/jmh/&quot;&gt;JMH&lt;/a&gt; blackhole as previously, but instead returning it to the framework, which promises to make sure that the result is referenced so that the benchmark computation has to be performed. Also note that, nervous of other processor optimisations, I use a random variable rather than a fixed value for each benchmark execution when dealing with primitives.]&lt;/p&gt;

&lt;p&gt;The simplest thing we can do is to create a function reference and invoke that, rather than invoking the function directly.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Benchmark
    fun invoke_via_reference(intState: IntState) : Int {
        return (::aFunction)(intState.randomInt)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This turns out to be between 1% and 2% slower than the baseline.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun `invoke via reference is slower than plain invocation`() {
        assertThat(this::baseline, probablyFasterThan(this::invoke_via_reference, byAFactorOf = 0.01))
        assertThat(this::baseline, ! probablyFasterThan(this::invoke_via_reference, byAFactorOf = 0.02))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This result is surprising in two ways.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;As far as I can see, the compiler could compile invoke_via_reference to the same code as the baseline.&lt;/li&gt;
  &lt;li&gt;Given that it hasn’t; &amp;lt; 2% is really not much slower.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So let’s fall back to the bytecode&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final baseline(LcostOfKotlin/primitives/IntState;)I
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC &quot;intState&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 16 L1
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/primitives/IntState.getRandomInt ()I
    INVOKESTATIC costOfKotlin/invoking/InvokingKt.aFunction (I)I
    IRETURN
    
public final invoke_via_reference(LcostOfKotlin/primitives/IntState;)I
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC &quot;intState&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 22 L1
    GETSTATIC costOfKotlin/invoking/Invoking$invoke_via_reference$1.INSTANCE : LcostOfKotlin/invoking/Invoking$invoke_via_reference$1;
    CHECKCAST kotlin/jvm/functions/Function1
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/primitives/IntState.getRandomInt ()I
    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
    INVOKEINTERFACE kotlin/jvm/functions/Function1.invoke (Ljava/lang/Object;)Ljava/lang/Object;
    CHECKCAST java/lang/Number
    INVOKEVIRTUAL java/lang/Number.intValue ()I
    IRETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Instead of just &lt;code&gt;INVOKESTATIC costOfKotlin/invoking/InvokingKt.aFunction&lt;/code&gt;, &lt;code&gt;invoke_via_reference&lt;/code&gt; has additional calls to get the instance of the function as a function type, check that it is the right type, box the parameter because there are no primitive specialisations of the function types, invoke the function through its interface with the boxed parameter, and finally unbox the result. All this costs just ~1.5% throughput.&lt;/p&gt;

&lt;p&gt;[Writing this I realise that if the benchmark tax (calls to &lt;code&gt;checkParamaterIsNotNull&lt;/code&gt; and &lt;code&gt;IntState.getRandomInt&lt;/code&gt;) is high, it reduces the apparent cost of the invocations we actually want to measure. In this case I don’t believe that they are - in particular note that the random int is calculated outside the benchmark not on demand.]&lt;/p&gt;

&lt;p&gt;Anyhoo; the point of first class functions is to be passed around. Let’s simulate that by passing them to something whose job it is to invoke them.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;inline fun &amp;lt;T&amp;gt; applier(t: T, f: (T) -&amp;gt; T) = f(t)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can benchmark lambdas and function references.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Benchmark
    fun passed_as_lambda(intState: IntState) : Int {
        return applier(intState.randomInt) { aFunction(it ) }
    }

    @Benchmark
    fun passed_as_function_reference(intState: IntState) : Int {
        return applier(intState.randomInt, ::aFunction)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For the data that I’ve gathered, these are statistically indistinguishable from the baseline!&lt;/p&gt;

&lt;p&gt;Again, there are two reasons for that exclamation mark. Let’s look at the bytecode.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public final passed_as_lambda(LcostOfKotlin/primitives/IntState;)I
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC &quot;intState&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 27 L1
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/primitives/IntState.getRandomInt ()I
    ISTORE 2
   L2
    LINENUMBER 66 L2
    ILOAD 2
    ISTORE 3
   L3
    LINENUMBER 27 L3
    ILOAD 3
    INVOKESTATIC costOfKotlin/invoking/InvokingKt.aFunction (I)I
   L4
   L5
    NOP
   L6
    IRETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;[&lt;code&gt;passed_as_function_reference&lt;/code&gt; is identical &lt;a href=&quot;https://www.merriam-webster.com/dictionary/mutatis%20mutandis&quot;&gt;&lt;em&gt;mutatis mutandis&lt;/em&gt;&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;Pretentious! Moi? Anyhoo; because of the wonders of inline functions, we haven’t had to pay the price of boxing and unboxing our int, nor of invoking a function type through its interface. If you ignore the line numbers and loading and storing - this is the same code as the baseline. Which is remarkable.&lt;/p&gt;

&lt;p&gt;And yet it isn’t the same code as the baseline, because of the loading and storing, which are setting things up on the JVM stack to be used in the function. In the baseline the result of INVOKEVIRTUAL of &lt;code&gt;getRandomInt&lt;/code&gt; puts the argument to INVOKESTATIC &lt;code&gt;aFunction&lt;/code&gt; straight onto the operand stack. In this code the result of &lt;code&gt;getRandomInt&lt;/code&gt; is pulled from the stack into a local variable 2, which is pushed onto the stack in order to be stored in local variable 3, which is pushed onto the stack in order to be used by &lt;code&gt;aFunction&lt;/code&gt;. This faffing is a bit surprising, as is the fact that I can’t measure its cost in terms of benchmark speed.&lt;/p&gt;

&lt;p&gt;I think that the local variable hokey-cokey is required because we expect to be able to set a breakpoint in the &lt;code&gt;applier&lt;/code&gt; and see the values of its parameters, although that &lt;em&gt;may&lt;/em&gt; only explain one of the in-outs. My inability to detect any time taken in the dance may be because these are very fast instructions to execute, or it may be that HotSpot detects that they are not necessary and optimises them away. Your virtual machine mileage may vary.&lt;/p&gt;

&lt;p&gt;My brain hurts now, so just one more benchmark before lunch.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val aBlock: (Int) -&amp;gt; Int = { 2 * it }

    @Benchmark
    fun passed_as_value_of_function_type(intState: IntState) : Int {
        return applier(intState.randomInt, aBlock)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we invoke via a variable of function type, rather than directly with a lambda or function reference. In this case the speed is slower than the baseline and the other &lt;code&gt;applier&lt;/code&gt; applications by 1-2%. Why?&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;  public final passed_as_value_of_function_type(LcostOfKotlin/primitives/IntState;)I
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC &quot;intState&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 37 L1
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/primitives/IntState.getRandomInt ()I
    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;
    ASTORE 2
    INVOKESTATIC costOfKotlin/invoking/InvokingKt.getABlock ()Lkotlin/jvm/functions/Function1;
    ASTORE 3
   L2
    LINENUMBER 68 L2
    ALOAD 3
    ALOAD 2
    INVOKEINTERFACE kotlin/jvm/functions/Function1.invoke (Ljava/lang/Object;)Ljava/lang/Object;
   L3
    CHECKCAST java/lang/Number
    INVOKEVIRTUAL java/lang/Number.intValue ()I
    IRETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we pay the price of getting the value of &lt;code&gt;aBlock&lt;/code&gt;, and, because it is a function type and we are using a primitive, boxing and unboxing in order to call it, via its interface. This is this interesting because it shows that, for inline functions, the cost of the function depends not just on its definition, but also the code into which it is inlined.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>The Cost of Kotlin Language Features - Preliminary Results Part 2 - Strings</title>
   <link href="http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part2-strings.html"/>
   <updated>2017-10-08T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part2-strings</id>
   <content type="html">&lt;p&gt;This is Part 2 in a series examining &lt;em&gt;The Cost of Kotlin Language Features&lt;/em&gt; in preparation for my presentation at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; in November. The series consists of&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;benchmarks.html&quot;&gt;Lessons Learned Writing Java and Kotlin Microbenchmarks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part1-baselines.html&quot;&gt;Part 1 - Baselines&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part2-strings.html&quot;&gt;Part 2 - Strings&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part3-invocation.html&quot;&gt;Part 3 - Invocation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-4-nullable-primitives.html&quot;&gt;Part 4 - Nullable Primitives&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-5-properties.html&quot;&gt;Part 5 - Properties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’m publishing these results ahead of KotlinConf to give an opportunity for peer-review, so please do give me your feedback about the content, experimental method, code and conclusions. If you’re reading this before November 2017 it isn’t too late to save me from making a fool of myself in person, rather than just on the Internet.&lt;/p&gt;

&lt;p&gt;In this post I look at String interpolation, the language feature that allows you to embed Kotlin expressions inside strings.&lt;/p&gt;

&lt;p&gt;Let’s build the string &lt;code&gt;Hello World&lt;/code&gt; from its greeting and subject, in Java first.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public class JavaStrings {

    @Benchmark
    public void baseline(StringState state, Blackhole blackhole) {
        blackhole.consume(state.getHello());
        blackhole.consume(state.getWorld());
    }

    @Benchmark
    public void concat(StringState state, Blackhole blackhole) {
        blackhole.consume(state.getHello() + &quot; &quot; + state.getWorld());
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we just concatenate two strings passed into the benchmark, separated by a space. See &lt;a href=&quot;2017-10-08-cost-of-kotlin-preliminary-results-part1-baselines.html&quot;&gt;Part 1&lt;/a&gt; for an explanation of the &lt;code&gt;state&lt;/code&gt; and &lt;code&gt;blackhole&lt;/code&gt; parameters.&lt;/p&gt;

&lt;p&gt;In Kotlin we could write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;open class KotlinStrings {

    @Benchmark
    fun baseline(state: StringState, blackhole: Blackhole) {
        blackhole.consume(state.hello)
        blackhole.consume(state.world)
    }

    @Benchmark
    fun concat(state: StringState, blackhole: Blackhole) {
        blackhole.consume(&quot;${state.hello} ${state.world}&quot;)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Graphically the throughput for a particular test run looks like this&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/strings-f1-w10-m500-run2.png&quot; alt=&quot;A Sample Strings Run&quot; /&gt;&lt;/p&gt;

&lt;p&gt;A visual inspection suggests that the Kotlin version may be as quick as the Java one, and indeed, for the data I have, I cannot tell them apart.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    @Test
    fun `cannot detect the difference between Java and Kotlin`() {
        assertThat(JavaStrings::concat, ! probablyDifferentTo(KotlinStrings::concat))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In other words, “We cannot say that (the mean throughput of the Java version is different than the mean throughput of the Kotlin version for a 95% confidence)”.&lt;/p&gt;

&lt;p&gt;Whilst this is true for the data that I have, I suspect that it is not true to say that there is no cost to Kotlin’s string interpolation. Examining the bytecode for the Java (v 1.8.0_131) version we see.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;  public concat(LcostOfKotlin/strings/StringState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
   L0
    LINENUMBER 18 L0
    ALOAD 2
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.&amp;lt;init&amp;gt; ()V
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/strings/StringState.getHello ()Ljava/lang/String;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    LDC &quot; &quot;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/strings/StringState.getWorld ()Ljava/lang/String;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (Ljava/lang/Object;)V
   L1
    LINENUMBER 19 L1
    RETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;while the Kotlin (v 1.1.4) has&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;  public final concat(LcostOfKotlin/strings/StringState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
     [null checks, see Part 1]
   L1
    LINENUMBER 21 L1
    ALOAD 2
    NEW java/lang/StringBuilder
    DUP
    INVOKESPECIAL java/lang/StringBuilder.&amp;lt;init&amp;gt; ()V
    LDC &quot;&quot;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/strings/StringState.getHello ()Ljava/lang/String;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    BIPUSH 32
    INVOKEVIRTUAL java/lang/StringBuilder.append (C)Ljava/lang/StringBuilder;
    ALOAD 1
    INVOKEVIRTUAL costOfKotlin/strings/StringState.getWorld ()Ljava/lang/String;
    INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;
    INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (Ljava/lang/Object;)V
   L2
    LINENUMBER 22 L2
    RETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Both create a StringBuilder and then append the parts of the string, but the Kotlin compiler has appended a vestigial empty string representing the parts of the template string before the first substitution. As it is hard to believe that appending an empty string to a StringBuffer is free, the Kotlin code must be slower, just not, in this case, detectably so.&lt;/p&gt;

&lt;p&gt;As a aside, both the Kotlin and the Java compilers miss the trick of initialising the StringBuilder with the first part of the concatenation - both cases should really generate code equivalent to&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;new StringBuilder(state.getHello()).append(state.getWorld())
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Apart from the un-needed empty string, I found no places where Kotlin string interpolation had any cost over vanilla Java. Indeed where strings are known constant at compile time, they are composed then.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun `the compiler optimizes this to a constant`() = &quot;${&quot;hello&quot;} ${&quot;world&quot;}&quot;

    fun `and even this`() = &quot;${&quot;${&quot;hello&quot; + &quot; &quot; + &quot;world&quot;}&quot;}&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;both compile to&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    LDC &quot;hello world&quot;
    ARETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;although&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private val hello = &quot;hello&quot;
private val world = &quot;world&quot;

fun `this is not a constant expression`() = &quot;$hello $world&quot;
&lt;/code&gt;&lt;/pre&gt;

</content>
 </entry>
 
 <entry>
   <title>The Cost of Kotlin Language Features - Preliminary Results Part 1 - Baselines</title>
   <link href="http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part1-baselines.html"/>
   <updated>2017-10-07T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/cost-of-kotlin-preliminary-results-part1-baselines</id>
   <content type="html">&lt;p&gt;Following on from my last post &lt;a href=&quot;benchmarks.html&quot;&gt;Lessons Learned Writing Java and Kotlin Microbenchmarks&lt;/a&gt;, this post presents some preliminary results examining &lt;em&gt;The Cost of Kotlin Language Features&lt;/em&gt; in preparation for my presentation at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; in November.&lt;/p&gt;

&lt;p&gt;The code behind the investigation is all available &lt;a href=&quot;https://github.com/dmcg/kostings&quot;&gt;on GitHub&lt;/a&gt;. There you will find &lt;a href=&quot;https://github.com/dmcg/kostings/tree/master/src/main/java/com/oneeyedmen/kostings&quot;&gt;a framework&lt;/a&gt; that uses &lt;a href=&quot;http://openjdk.java.net/projects/code-tools/jmh/&quot;&gt;JMH&lt;/a&gt; to run benchmarks, and then runs JUnit tests on the results to check assertions about their relative speed. The &lt;a href=&quot;https://github.com/dmcg/kostings/tree/master/src/main/java/costOfKotlin&quot;&gt;actual benchmarks and tests&lt;/a&gt; that I’m running are also there, along with &lt;a href=&quot;https://github.com/dmcg/kostings/tree/master/results&quot;&gt;benchmark results&lt;/a&gt; and the &lt;a href=&quot;https://github.com/dmcg/kostings/tree/master/canonical-results&quot;&gt;sets of those results that are used in the tests&lt;/a&gt;. The separation allows me to reject results that are suspect for any of the reasons discussed in my previous post.&lt;/p&gt;

&lt;p&gt;Note that, since that post, &lt;a href=&quot;https://twitter.com/johnsnolan&quot;&gt;John Nolan&lt;/a&gt; has helped greatly with the statistics of comparing benchmarks and contributed the statistical comparators that the framework uses.&lt;/p&gt;

&lt;p&gt;I’m publishing these results ahead of KotlinConf to give an opportunity for peer-review, so please do give me your feedback about the content, experimental method, code and conclusions. If you’re reading this before November 2017 it isn’t too late to save me from making a fool of myself in person, rather than just on the Internet.&lt;/p&gt;

&lt;p&gt;With this in mind, let’s dive straight in and look at the baseline tests.&lt;/p&gt;

&lt;p&gt;First Java&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public class JavaBaseline {
    @Benchmark
    public void baseline(StringState state, Blackhole blackhole) {
        blackhole.consume(state);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then Kotlin&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;open class KotlinBaseline {
    @Benchmark
    fun baseline(state: StringState, blackhole: Blackhole) {
        blackhole.consume(state)
    }

    @Test
    fun `java is quicker but not by much`() {
        assertThat(JavaBaseline::baseline, probablyFasterThan(this::baseline, byAFactorOf = 0.005))
        assertThat(JavaBaseline::baseline, ! probablyFasterThan(this::baseline, byAFactorOf = 0.01))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With JMH benchmarks it is important that data used in the benchmark is passed in from the outside world (via &lt;code&gt;State&lt;/code&gt; objects), and consumed by the benchmark framework (using the &lt;code&gt;Blackhole&lt;/code&gt;)- these limit optimisations that would allow some or all of the benchmark code to be skipped altogether. As pretty much any JMH test requires the use of these devices, I’ve included them in the baseline benchmarks.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;@Test&lt;/code&gt; we see assertions about the relative performance of the &lt;code&gt;@Benchmark&lt;/code&gt; methods. The test shows that the Java code is quicker by between 0.5 % and 1%, with the default Confidence Interval of 95%.&lt;/p&gt;

&lt;p&gt;Here is a sample benchmark run shown graphically (the error bars are the mean error with 99.9% confidence).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/baselines-f1-w10-m500-run2.png&quot; alt=&quot;A Sample Baseline Run&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Given that the Kotlin and Java look functionally identical, you might expect that we shouldn’t be able to detect any difference in the runtime of the code. There is a subtle difference though, revealed when we examine the bytecode emitted by the Java compiler.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public baseline(LcostOfKotlin/strings/StringState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
   L0
    LINENUMBER 12 L0
    ALOAD 2
    ALOAD 1
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (Ljava/lang/Object;)V
   L1
    LINENUMBER 13 L1
    RETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;compared to that from the Kotlin compiler&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;  public final baseline(LcostOfKotlin/strings/StringState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 1
   L0
    ALOAD 1
    LDC &quot;state&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
    ALOAD 2
    LDC &quot;blackhole&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 14 L1
    ALOAD 2
    ALOAD 1
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (Ljava/lang/Object;)V
   L2
    LINENUMBER 15 L2
    RETURN
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The Kotlin compiler always checks that arguments passed to non-nullable parameters are, in fact, not null (at least for public functions). I suppose that in a pure Kotlin world these could be dispensed with, and there is a compiler flag to disable them, but the reasoning goes that any old Java code could be invoking your method with nulls, so it’s better to find this out as early as possible.&lt;/p&gt;

&lt;p&gt;This price is paid for invocation of every public Kotlin method, so it’s as well that the check is relatively cheap. In this case you have to run the benchmarks for many iterations before you can see a statistically significant effect.&lt;/p&gt;

&lt;p&gt;In the rest of this series I’ll rarely compare Java results directly to Kotlin, but when I do, it’s worth remembering that at least some of any slowdown detected will be due to parameter null checks rather than the rest of the benchmark method.&lt;/p&gt;

&lt;p&gt;I hope to have the next installment of this series, covering string interpolation, published in the next few days.&lt;/p&gt;

&lt;p&gt;Edit - here are the parts as I write them&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;benchmarks.html&quot;&gt;Lessons Learned Writing Java and Kotlin Microbenchmarks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part1-baselines.html&quot;&gt;Part 1 - Baselines&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part2-strings.html&quot;&gt;Part 2 - Strings&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part3-invocation.html&quot;&gt;Part 3 - Invocation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-4-nullable-primitives.html&quot;&gt;Part 4 - Nullable Primitives&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;cost-of-kotlin-preliminary-results-part-5-properties.html&quot;&gt;Part 5 - Properties&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</content>
 </entry>
 
 <entry>
   <title>Lessons Learned Writing Java and Kotlin Microbenchmarks</title>
   <link href="http://0.0.0.0:4000/benchmarks.html"/>
   <updated>2017-09-16T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/benchmarks</id>
   <content type="html">&lt;p&gt;I’m presenting a session, &lt;em&gt;The Cost of Kotlin Language Features&lt;/em&gt;, at &lt;a href=&quot;http://kotlinconf.com&quot;&gt;KotlinConf&lt;/a&gt; in November. In the best scientific tradition I proposed the session because I was interested in the topic, knew little about it, and wanted to be forced to learn. That’ll teach me!&lt;/p&gt;

&lt;p&gt;Coincidentally, the day that my proposal was accepted, Christophe Beyls published a series of 3 articles on Medium titled &lt;a href=&quot;https://medium.com/@BladeCoder/exploring-kotlins-hidden-costs-part-1-fbb9935d9b62&quot;&gt;Exploring Kotlin’s hidden costs&lt;/a&gt;. Well that was pleasing - Jetbrains were paying for me to go to San Francisco and Christophe was doing all the work! I filed the links for later &lt;del&gt;&lt;a href=&quot;http://www.youtube.com/watch?v=wNel8RwSLyE&amp;amp;t=0m35s&quot;&gt;plagarism&lt;/a&gt;&lt;/del&gt; research and got on with booking flights.&lt;/p&gt;

&lt;p&gt;Later that month Renato Athaydes went even further. Christophe had inferred costs by examining the generated bytecode, but Renato pointed out that it is notoriously difficult to predict Java’s performance from examining the code because of the HotSpot JIT compiler. So he wrote some &lt;a href=&quot;http://openjdk.java.net/projects/code-tools/jmh/&quot;&gt;JMH&lt;/a&gt; benchmarks to measure the actual performance and published the results in &lt;a href=&quot;https://sites.google.com/a/athaydes.com/renato-athaydes/posts/kotlinshiddencosts-benchmarks&quot;&gt;Kotlin’s hidden costs - Benchmarks&lt;/a&gt;. As my conference proposal had promised both bytecode analysis and benchmarks, this concluded my work and I got on with my day job.&lt;/p&gt;

&lt;p&gt;Except that there was a nagging doubt remaining - both from my own reading of his results and &lt;a href=&quot;https://www.reddit.com/r/programming/comments/6jegsg/kotlin_hidden_costs_benchmarks/&quot;&gt;other peoples comments&lt;/a&gt;. Oh dear, I am actually going to have to understand this stuff if I’m to present at a conference.&lt;/p&gt;

&lt;p&gt;So I set to writing some &lt;a href=&quot;https://github.com/dmcg/kostings&quot;&gt;benchmarks of my own&lt;/a&gt; to understand how they work. (At the time of writing these are work in progress, so I’d welcome feedback, but please be gentle.) I quickly learned how hard it is to force a computer to do any calculation that you then ignore, and not to effectively inline any value that you don’t change. A good guide to working through these issues is &lt;a href=&quot;http://tutorials.jenkov.com/java-performance/jmh.html&quot;&gt;JMH Java Microbenchmark Harness&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Even once I had introduced &lt;code&gt;@State&lt;/code&gt;, used a &lt;code&gt;Blackhole&lt;/code&gt;, and run enough warmup iterations that HotSpot would do its thing, I still got some perplexing results. To understand why they were odd we need some more background.&lt;/p&gt;

&lt;h2 id=&quot;how-jmh-runs-benchmarks&quot;&gt;How JMH runs benchmarks&lt;/h2&gt;

&lt;p&gt;JMH works (by default) by running benchmark methods in a tight loop until 1 second has elapsed, counting the number of loops in that time. These 1 s iterations are repeated a configurable number of times, proceeded by a configurable number of 1 s warmup iterations whose times are reported, but ignored. All iterations for a single benchmark are performed in a separate VM than that orchestrating the measurements, with new VMs created to an outer batch.&lt;/p&gt;

&lt;p&gt;The default settings are 10 (serial) JVM forks, in each of which 20 warmup iterations are performed followed by 20 measurements, for a total of 200 1 s iterations per benchmark.&lt;/p&gt;

&lt;p&gt;You can select multiple benchmarks for a run by regex, these will be run one after the other by the same orchestrator. So if there are 3 benchmarks there will be 30 forked VMs created, and 600 total measurement iterations.&lt;/p&gt;

&lt;p&gt;Here is an example of JMH output at the start of a run&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# JMH version: 1.19
# VM version: JDK 1.8.0_131, VM 25.131-b11
# VM invoker: /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin/java
# VM options: &amp;lt;none&amp;gt;
# Warmup: 20 iterations, 1 s each
# Measurement: 20 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: com.oneeyedmen.kostings.baselines.JavaBaseline.baseline

# Run progress: 0.00% complete, ETA 00:13:20
# Fork: 1 of 10
# Warmup Iteration   1: 293010554.087 ops/s
# Warmup Iteration   2: 296380175.612 ops/s
...
# Warmup Iteration  20: 367022161.575 ops/s
Iteration   1: 369132107.601 ops/s
Iteration   2: 368540396.014 ops/s
...
Iteration  20: 355492595.855 ops/s

# Run progress: 5.00% complete, ETA 00:12:56
# Fork: 2 of 10
# Warmup Iteration   1: 267261211.186 ops/s
...
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;how-jmh-reports-benchmarks&quot;&gt;How JMH reports benchmarks&lt;/h2&gt;

&lt;p&gt;Once all the measurement iterations in all the forks for a benchmark are complete, JMH reports the average throughput for that benchmark, together with the 99.9% confidence interval, assuming a Gaussian distribution. So that run finished with this report&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Run complete. Total time: 00:13:31

Benchmark                 Mode  Cnt          Score         Error  Units
JavaBaseline.baseline    thrpt  200  359400874.797 ± 3190513.351  ops/s
KotlinBaseline.baseline  thrpt  200  363343435.012 ± 5184390.204  ops/s
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There’s a lot of spurious precision going on there, making it hard to see the wood for the trees. Luckily JMH can also output to a CSV file,&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;Benchmark&quot;,&quot;Mode&quot;,&quot;Threads&quot;,&quot;Samples&quot;,&quot;Score&quot;,&quot;Score Error (99.9%)&quot;,&quot;Unit&quot;
&quot;com.oneeyedmen.kostings.baselines.JavaBaseline.baseline&quot;,&quot;thrpt&quot;,1,200,359400874.797,3190513.351,&quot;ops/s&quot;
&quot;com.oneeyedmen.kostings.baselines.KotlinBaseline.baseline&quot;,&quot;thrpt&quot;,1,200,363343435.012,5184390.204,&quot;ops/s&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we can use that to generate graphs that humans can read. Here we show the 99.9% confidence interval with error bars.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/baselines-f10-w20-m20-random-run.png&quot; alt=&quot;Baselines Histogram&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;interpreting-relative-results&quot;&gt;Interpreting relative results&lt;/h2&gt;

&lt;p&gt;Here is the code that was being benchmarked.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public class JavaBaseline {
    @Benchmark public void baseline(StringState state, Blackhole blackhole) {
        blackhole.consume(state);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;open class KotlinBaseline {
    @Benchmark fun baseline(state: StringState, blackhole: Blackhole) {
        blackhole.consume(state)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Looking at the histogram, this leaves us with a problem - the Kotlin code seems to be quicker, despite doing the same thing. The results say that there is a 99.9% chance that the Java is not faster than 362,591,388 ops/s, and a 99.9% chance that the Kotlin as not slower than 358,159,044 ops/s. This leaves an overlap between their confidence levels that allows Java to be faster, but with not much confidence (is someone able to do the maths?).&lt;/p&gt;

&lt;p&gt;Is it possible that Java is likely slower than Kotlin for this benchmark, as the results suggest?&lt;/p&gt;

&lt;p&gt;Let’s look at the bytecode. First Java&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  // access flags 0x1
  public baseline(Lcom/oneeyedmen/kostings/strings/StringState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
   L0
    LINENUMBER 12 L0
    ALOAD 2
    ALOAD 1
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (Ljava/lang/Object;)V
   L1
    LINENUMBER 13 L1
    RETURN
   L2
    LOCALVARIABLE this Lcom/oneeyedmen/kostings/baselines/JavaBaseline; L0 L2 0
    LOCALVARIABLE state Lcom/oneeyedmen/kostings/strings/StringState; L0 L2 1
    LOCALVARIABLE blackhole Lorg/openjdk/jmh/infra/Blackhole; L0 L2 2
    MAXSTACK = 2
    MAXLOCALS = 3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then Kotlin&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  // access flags 0x11
  public final baseline(Lcom/oneeyedmen/kostings/strings/StringState;Lorg/openjdk/jmh/infra/Blackhole;)V
  @Lorg/openjdk/jmh/annotations/Benchmark;()
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 1
   L0
    ALOAD 1
    LDC &quot;state&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
    ALOAD 2
    LDC &quot;blackhole&quot;
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 15 L1
    ALOAD 2
    ALOAD 1
    INVOKEVIRTUAL org/openjdk/jmh/infra/Blackhole.consume (Ljava/lang/Object;)V
   L2
    LINENUMBER 16 L2
    RETURN
   L3
    LOCALVARIABLE this Lcom/oneeyedmen/kostings/baselines/KotlinBaseline; L0 L3 0
    LOCALVARIABLE state Lcom/oneeyedmen/kostings/strings/StringState; L0 L3 1
    LOCALVARIABLE blackhole Lorg/openjdk/jmh/infra/Blackhole; L0 L3 2
    MAXSTACK = 2
    MAXLOCALS = 3
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So Kotlin is checking the parameters aren’t null, and running the exact same code as the Java. Unless HotSpot is able to deduce that some later code doesn’t have to be run because Kotlin has made this check, I can’t see any way that the Java can be slower, but our benchmarks show that it is, probably.&lt;/p&gt;

&lt;p&gt;Running a number of different benchmarks, with different fork counts, and different numbers of iterations, produced many of these perverse results. The numbers &lt;a href=&quot;https://en.wikipedia.org/wiki/How_to_Lie_with_Statistics&quot;&gt;can’t lie&lt;/a&gt;, but are we asking them the right question?&lt;/p&gt;

&lt;h2 id=&quot;systematic-errors&quot;&gt;Systematic Errors&lt;/h2&gt;

&lt;p&gt;The confidence intervals given by JMH are based only on the measurements that it has taken - they aren’t a reflection of the actual truth. In order to get an idea of what causes the measurement variation that we interpret as errors, we have to drill further into the data.&lt;/p&gt;

&lt;p&gt;In addition to the CSV output, JMH has a JSON output.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
    &quot;lots-of-stuff-deleted&quot;: &quot;...&quot;
    &quot;warmupIterations&quot; : 20,
    &quot;warmupTime&quot; : &quot;1 s&quot;,
    &quot;warmupBatchSize&quot; : 1,
    &quot;measurementIterations&quot; : 20,
    &quot;measurementTime&quot; : &quot;1 s&quot;,
    &quot;measurementBatchSize&quot; : 1,
    &quot;primaryMetric&quot; : {
        &quot;score&quot; : 3.656186120562128E8,
        &quot;scoreError&quot; : 1833316.6776747273,
        &quot;scoreConfidence&quot; : [
            3.637852953785381E8,
            3.674519287338875E8
        ],
        &quot;scorePercentiles&quot; : {
            &quot;0.0&quot; : 3.168042199792653E8,
            &quot;50.0&quot; : 3.654796412185938E8,
            &quot;90.0&quot; : 3.7526561404113406E8,
            &quot;95.0&quot; : 3.781350703702088E8,
            &quot;99.0&quot; : 3.821109699100871E8,
            &quot;99.9&quot; : 3.8282245766638625E8,
            &quot;99.99&quot; : 3.8282245766638625E8,
            &quot;99.999&quot; : 3.8282245766638625E8,
            &quot;99.9999&quot; : 3.8282245766638625E8,
            &quot;100.0&quot; : 3.8282245766638625E8
        },
        &quot;scoreUnit&quot; : &quot;ops/s&quot;,
        &quot;rawData&quot; : [
            [
                3.599636727894533E8,
                3.670631984977747E8,
                3.678476209011342E8,
                3.750361228656685E8
  
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we have access to each measurement. I don’t have the data for the run we’ve just seen, but here are the histograms
for another set of benchmarks.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/strings-f10-w20-m20-run3.png&quot; alt=&quot;Strings Histogram Suspect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;There is a lot of uncertainty in that &lt;code&gt;KotlinStrings.baseline&lt;/code&gt;, I wonder what the measurements look like?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/strings-f10-w20-m20-run3.samples.png&quot; alt=&quot;Strings Measurements Suspect&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Whoa! I don’t know what went on at the end of that run, but it wasn’t normal. &lt;code&gt;JavaStrings.Concat&lt;/code&gt; seems to have taken a wobble around iteration 60 as well. Clearly these results should not be trusted.&lt;/p&gt;

&lt;p&gt;Another run gives the following results.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/strings-f10-w20-m20-run5.samples.png&quot; alt=&quot;Strings Measurements Better&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/strings-f10-w20-m20-run5.png&quot; alt=&quot;Strings Histogram Better&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Note the much smaller error bars reflecting the lack of variation in the &lt;code&gt;KotlinStrings.baseline&lt;/code&gt; measurements.&lt;/p&gt;

&lt;h2 id=&quot;causes-of-systematic-errors&quot;&gt;Causes of Systematic Errors&lt;/h2&gt;

&lt;p&gt;What causes dropouts like these? I suppose anything that causes CPU or memory bandwidth to be switched away from the benchmark VM, which is many of the little conveniences that we expect computers to do for us without being asked. To get stable benchmarks on my MacBook Pro I have had to:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Disable Time Machine, which otherwise backs up after a period of user inactivity.&lt;/li&gt;
  &lt;li&gt;Disable CrashPlan, ditto.&lt;/li&gt;
  &lt;li&gt;Close IntelliJ, so that it doesn’t refresh it’s indices after noticing the results files being written.&lt;/li&gt;
  &lt;li&gt;Make sure Finder isn’t viewing the results folder.&lt;/li&gt;
  &lt;li&gt;Disable various agents (Dropbox, Google Earth) which check for updates periodically.&lt;/li&gt;
  &lt;li&gt;Disable the screensaver.&lt;/li&gt;
  &lt;li&gt;Disable switching off the screen after inactivity.&lt;/li&gt;
  &lt;li&gt;Disable sleep after inactivity.&lt;/li&gt;
  &lt;li&gt;Not use the computer while the benchmarks are running.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Even then I must have missed something, because looking at the results I still get occasional dropouts, so I now make it a rule to view the graph of throughput for each benchmark batch, and to re-run those which show obviously non-random variation.&lt;/p&gt;

&lt;h2 id=&quot;further-investigation&quot;&gt;Further Investigation&lt;/h2&gt;

&lt;p&gt;Plotting a histogram of the distribution of measurements might give insight into whether they are random or systematic errors. No-doubt some statistics could be brought to bear to automatically reject results that were not sufficiently Gaussian.&lt;/p&gt;

&lt;p&gt;I suspect that Intel Turbo-Boost, where a processor ramps up its clock in response to demand, but then slows down again as it heats up, may be another cause of systematic errors.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Despite the best efforts of JMH to allow the writing of reliable micro-benchmarks, the modern computing environment is complex and it is hard to remove all systematic errors. It is not enough to look at the summarised results - you have to examine the distribution of benchmark measurements to have confidence in the numbers.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;postscript---speeding-up-benchmarks&quot;&gt;Postscript - Speeding up benchmarks&lt;/h2&gt;

&lt;p&gt;Needless to say, benchmarking can take time. The default settings take at least 10 * (20 + 20) = 400 s per benchmark. A faster machine doesn’t help much, because each measurement takes 1 s - you just get better fidelity in that measurement. You &lt;em&gt;can&lt;/em&gt; speed up a run by scrimping on the warmups - looking at the warmup iteration results for my benchmarks they don’t get noticeably faster after the 3rd iteration, so spending 20 s warming up is just wasting good loops, as this graph, of throughput against iteration with no warmup, shows.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;assets/baselines-f1-w0-m20-warming-up.samples.png&quot; alt=&quot;Warmup&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ideally it would be nice to give JMH a target confidence and have it continue to run a benchmark until that level was reached.&lt;/p&gt;

&lt;p&gt;I have also come to the conclusion that the default of 10 forks per benchmark needlessly slows the test run. As long as each benchmark is run in its own VM, it is significantly quicker to run 200 iterations in that than 20 in each of 10. There may be some situations in which the forking is important, but for the micro-benchmarks I am running I have not yet detected any unexpected behaviour using a single fork.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Chapter 1 - Spike</title>
   <link href="http://0.0.0.0:4000/spike.html"/>
   <updated>2017-06-16T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/spike</id>
   <content type="html">&lt;p&gt;{aside}
This is a draft of Chapter 1 of a book, tentatively titled “Programming Episodes”. I’m publishing it here for feedback - essentially I’d like to know whether to carry on writing or get a real job this summer. If you make it to the end, I’d be really grateful if you’d let me know what you think.
{/aside}&lt;/p&gt;

&lt;h1 id=&quot;chapter-1---spike&quot;&gt;Chapter 1 - Spike&lt;/h1&gt;

&lt;p&gt;I’m writing this in Lisbon airport, an hour before my flight back to London is due to leave. On this holiday I’ve decided I’m pretty committed to writing this book, and now I’m wondering what technologies I should use for its production.&lt;/p&gt;

&lt;p&gt;What criteria should I use to make the decision? Well the working title of the book is “Programming Episodes - learning modern development by example” so that might help. Defining modern development is something that I hope will become clear by the end, but as I think it through, I realise that deciding how to write the book is fundamentally an engineering decision. Engineering is about trade-offs, choice, optimisation. It’s about making the best use of your time or your client’s money. And very often in programming that comes down to trading the cost to make something now against the cost of fixing it later.&lt;/p&gt;

&lt;p&gt;I know that this book will take a long time to write, and I also know that it will be full of code samples that we’d both like to actually work by the time you come to read them. So I’m looking for a way that I can mix code and prose in a way that is easy to write and maintain.&lt;/p&gt;

&lt;p&gt;And that’s why these words are being written into the IntelliJ IDE rather than Word. They are plain text now, although I’m already thinking of them as &lt;a href=&quot;https://daringfireball.net/projects/markdown/&quot;&gt;Markdown&lt;/a&gt; - I just haven’t &lt;em&gt;needed&lt;/em&gt; to emphasise anything yet. I suspect that this prose will end up as comments in &lt;a href=&quot;https://kotlinlang.org/&quot;&gt;Kotlin&lt;/a&gt; source files, and that some sort of build system will put the book together for me. In fact, if you’re reading this on paper you can’t see it yet, but this file is already surrounded by a &lt;a href=&quot;https://gradle.org/&quot;&gt;Gradle&lt;/a&gt; build and is in the context of a Git repository. This is the way that modern development projects in Kotlin will start, and so it feels rather fitting that the book does too.&lt;/p&gt;

&lt;h2 id=&quot;the-first-kotlin-file&quot;&gt;The First Kotlin File&lt;/h2&gt;

&lt;p&gt;Risk reduction is high on the list of modern programming concerns. I want to know that the idea of embedding the content of this book in its own source code is viable. So I’m going to start with a spike - a prototype that goes deep into the heart of the problem but doesn’t attempt breadth. This way we hope to find major problems that might scupper an idea with the least effort.&lt;/p&gt;

&lt;p&gt;I’m typing this text as comments into a Kotlin source file called &lt;code&gt;2-spike.kt&lt;/code&gt;. Kotlin uses the same &lt;code&gt;/* block comment markers */&lt;/code&gt; as Java and C. So far I’ve found that the markers don’t get in the way of my text, but that I also don’t get a nice Markdown preview of the formatting. That’s alright though, as the nature of Markdown is that I can *see* the formatting even though it’s only characters.&lt;/p&gt;

&lt;p&gt;So text is OK. What about code?&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;import org.junit.Test
import kotlin.test.assertEquals

class SpikeTest {

    @Test fun `2 plus 2 is 4`() {
        assertEquals(4, add(2, 2))
    }
}

fun add(a: Int, b: Int) = a + b
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;{aside}
That’s a &lt;a href=&quot;http://junit.org/junit4/&quot;&gt;JUnit 4&lt;/a&gt; test written in Kotlin. I’m going assume that you can read and understand JUnit tests, and at least get the gist of Kotlin when it is written as a direct translation of Java.
{/aside}&lt;/p&gt;

&lt;p&gt;Well I can run that directly in the IDE and from the Gradle build tool, so I guess that’s a start. Thinking ahead it occurs to me that I’m going to want to be able to write comments in the code. These could get confused with the comments that are the book text , so I’d better start using a different marker for the latter. Taking a lead from Javadoc, which &lt;em&gt;extends&lt;/em&gt; standard block comments, but doesn’t change their parsing by the compiler, I’m going to go with&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;⁠/*-
This is book text which the compiler will ignore.
⁠-*/

/* This is a standard comment block
 ⁠*/
fun the_compiler_will_process_this() {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;for now and see how it goes.&lt;/p&gt;

&lt;p&gt;It occurs to me that this is the opposite of the normal Markdown approach, where we can embed code inside blocks, with the text as the top level. Here the code is the top level, and the Markdown is embedded in it. The advantage is that we have to do nothing to our text to compile it, the disadvantage is that something is going to have to process the files to do something with the text before we can render the Markdown. That seems reasonable to me though, as I write code for a living, and an awful lot of that code does just this sort of thing to text. In fact, now that I have a programming task to do, I can see whether or not I can describe that task in a way that makes sense to both of us.&lt;/p&gt;

&lt;h2 id=&quot;first-attempt-at-publishing&quot;&gt;First Attempt at Publishing&lt;/h2&gt;

&lt;p&gt;Let’s write some code to take a mixed prose and source file and write a Markdown version. I’m not entirely sure what that output should look like yet, but I’ll know it when I see it. This is the sweet spot for &lt;a href=&quot;http://approvaltests.com/&quot;&gt;Approval Tests&lt;/a&gt;, which will allow us to make rapid progress but at the same time know when something that used to work doesn’t any more.&lt;/p&gt;

&lt;p&gt;When you run an Approval test it stores the output from the test, and compares it to a approved version of that output. If they differ, or if there was no approved version, the test fails. You could write this logic yourself, indeed I have, so I’ll use the &lt;a href=&quot;https://github.com/dmcg/okeydoke&quot;&gt;OkeyDoke&lt;/a&gt; Approval Tests library, which integrates with JUnit through a &lt;code&gt;Rule&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;OK, time to write some code.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class CodeExtractorTests {

    @Rule @JvmField val approver = approvalsRule()

    @Test fun writes_a_markdown_file_from_Kotlin_file() {
        val source = &quot;&quot;&quot;
        |/*-
        |Title
        |=====
        |This is Markdown paragraph
        |-*/
        |
        |/* This is a code comment
        |*/
        |fun aFunction() {
        |   return 42
        |}
        |/*-
        |More book text.
        |-*/
        &quot;&quot;&quot;.trimMargin()
        approver.assertApproved(translate(source))
    }
}

fun translate(source: String) = source
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here I’ve written an example file content as a Kotlin here document, and then, for now, an identity translate function just to get us running. Running the test creates a file &lt;code&gt;CodeExtractorTests.writes_a_markdown_file_from_Kotlin_file.actual&lt;/code&gt; with the contents&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;/*-
Title
=====
This is Markdown paragraph
-*/

/* This is a code comment
*/
fun aFunction() {
   return 42
}
/*-
More book text.
-*/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is what we &lt;code&gt;assertApproved&lt;/code&gt;. The test fails, as there was no approved content to compare with the actual. We can make it pass by approving the content with&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;cp 'CodeExtractorTests.writes_a_markdown_file_from_Kotlin_file.actual' 'CodeExtractorTests.writes_a_markdown_file_from_Kotlin_file.approved'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and running it again.&lt;/p&gt;

&lt;p&gt;Of course we have just approved something that we know to be incorrect, but we’re taking baby steps here. Now we need to improve the &lt;code&gt;translate&lt;/code&gt; function. I was about to start by stripping out the lines beginning with &lt;code&gt;/*-&lt;/code&gt; and &lt;code&gt;-*/&lt;/code&gt;, but if we do that first we’ll loose information about where the code starts. In fact thinking it through I realise that this page has code that we don’t want to view (the &lt;code&gt;package&lt;/code&gt; and &lt;code&gt;import&lt;/code&gt; statements at the top), and I’m sure that in general there will be other code that is required to compile but doesn’t contribute to the narrative. Maybe we need to explicitly mark code to be included.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Test fun writes_a_markdown_file_from_Kotlin_file() {
    val source = &quot;&quot;&quot;
    |package should.not.be.shown
    |/*-
    |Title
    |=====
    |This is Markdown paragraph
    |-*/
    |import should.not.be.shown
    |//`
    |/* This is a code comment
    |*/
    |fun aFunction() {
    |   return 42
    |}
    |//`
    |/*-
    |More book text.
    |-*/
    &quot;&quot;&quot;.trimMargin()
    approver.assertApproved(translate(source))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here I’ve used a line comment with a backtick &lt;code&gt;//&lt;/code&gt;`` to mark the beginning and end of the code we want to see.&lt;/p&gt;

&lt;p&gt;Now we can first implement the code to strip out the block comments that hide our prose from the Kotlin compiler&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun translate(source: String) = source.split(&quot;\n&quot;)
    .filterNot { it.startsWith(&quot;/*-&quot;) || it.startsWith(&quot;-*/&quot;) }
    .joinToString(&quot;\n&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first run of the test fails as the actual file is different from the approved - inspecting it I can see that the differences are indeed the stripped out block comment markers - the file is now&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;package should.not.be.shown
Title
=====
This is Markdown paragraph
import should.not.be.shown
//`
/* This is a code comment
*/
fun aFunction() {
   return 42
}
//`
More book text.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s get to work putting the code between our special markers into a Markdown code block.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun translate(source: String): String {
    var inCodeBlock = false
    var inTextBlock = false
    return source.split(&quot;\n&quot;)
        .map {
            when {
                !inCodeBlock &amp;amp;&amp;amp; it.startsWith(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = true
                    &quot;```kotlin&quot;
                }
                inCodeBlock &amp;amp;&amp;amp; it.startsWith(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = false
                    &quot;```&quot;
                }
                !inTextBlock &amp;amp;&amp;amp; it.startsWith(&quot;/*-&quot;) -&amp;gt; {
                    inTextBlock = true
                    &quot;&quot;
                }
                inTextBlock &amp;amp;&amp;amp; it.startsWith(&quot;-*/&quot;) -&amp;gt; {
                    inTextBlock = false
                    &quot;&quot;
                }
                inTextBlock -&amp;gt; it
                inCodeBlock -&amp;gt; it
                else -&amp;gt; &quot;&quot;
            }
        }
        .joinToString(&quot;\n&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I won’t pretend that was easy to write, or that I’m proud of it, but it does work, yielding&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;

Title
=====
This is Markdown paragraph


```kotlin
/* This is a code comment
*/
fun aFunction() {
   return 42
}
```

More book text.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that I’ve chosen to leave blank lines where markers and ignored text are for now, as they make making sense of the output easier.&lt;/p&gt;

&lt;p&gt;Now of course, I have to try the code on the file that I’m typing into right now, as that is the real point.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun main(args: Array&amp;lt;String&amp;gt;) {
    val markdown = translate(File(&quot;src/test/java/com/oneeyedmen/book/Chapter_01_Spike/01_c_Spike-First-Attempt-at-Publishing.kt&quot;).readText())
    File(&quot;build/delme&quot;).apply {
        mkdirs()
        resolve(&quot;out.md&quot;).writeText(markdown)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It doesn’t quite work as I expected - it doesn’t find publish code markers ('’’) when they are indented with spaces. I suppose we should add that case to our test suite.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Test fun writes_a_markdown_file_from_Kotlin_file() {
    val source = &quot;&quot;&quot;
    |package should.not.be.shown
    |/*-
    |Title
    |=====
    |This is Markdown paragraph
    |-*/
    |object HiddenContext {
    |  //`
    |  /* This is a code comment
    |  */
    |  fun aFunction() {
    |     return 42
    |  }
    |  //`
    |}
    |/*-
    |More book text.
    |-*/
    &quot;&quot;&quot;.trimMargin()
    approver.assertApproved(translate(source))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and implement quickly and dirtyly to see if it’s good.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun translate(source: String): String {
    var inCodeBlock = false
    var inTextBlock = false
    return source.split(&quot;\n&quot;)
        .map {
            when {
                !inCodeBlock &amp;amp;&amp;amp; it.trim().startsWith(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = true
                    &quot;```kotlin&quot;
                }
                inCodeBlock &amp;amp;&amp;amp; it.trim().startsWith(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = false
                    &quot;```&quot;
                }
                !inTextBlock &amp;amp;&amp;amp; it.trim().startsWith(&quot;/*-&quot;) -&amp;gt; {
                    inTextBlock = true
                    &quot;&quot;
                }
                inTextBlock &amp;amp;&amp;amp; it.trim().startsWith(&quot;-*/&quot;) -&amp;gt; {
                    inTextBlock = false
                    &quot;&quot;
                }
                inTextBlock -&amp;gt; it
                inCodeBlock -&amp;gt; it
                else -&amp;gt; &quot;&quot;
            }
        }
        .joinToString(&quot;\n&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This works, and, after fixing some places in this file that I had messed up the formatting, it works here too.&lt;/p&gt;

&lt;p&gt;It feels like there is something general trying to get out of that &lt;code&gt;inBlock..&lt;/code&gt; code, but we’ll come back to it when I’m less tired. I’ll just make a small change to make it look less bad.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun translate(source: String): String {
    var inCodeBlock = false
    var inTextBlock = false
    return source.split(&quot;\n&quot;)
        .map { line -&amp;gt;
            when {
                !inCodeBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = true
                    &quot;```kotlin&quot;
                }
                inCodeBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = false
                    &quot;```&quot;
                }
                !inTextBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;/*-&quot;) -&amp;gt; {
                    inTextBlock = true
                    &quot;&quot;
                }
                inTextBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;-*/&quot;) -&amp;gt; {
                    inTextBlock = false
                    &quot;&quot;
                }
                inTextBlock -&amp;gt; line
                inCodeBlock -&amp;gt; line
                else -&amp;gt; &quot;&quot;
            }
        }
        .joinToString(&quot;\n&quot;)
}

fun String.firstNonSpaceCharsAre(s: String) = this.trimStart().startsWith(s)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;combining-files&quot;&gt;Combining Files&lt;/h2&gt;

&lt;p&gt;We’re almost done in this first stint. The next thing I need to do to increase my confidence that this is working is to combine all the sections of this chapter into a whole, so that I and others can read it.&lt;/p&gt;

&lt;p&gt;This text is being written into &lt;code&gt;01_d_Spike-Combining-Files.kt&lt;/code&gt;, in a directory (actually Java / Kotlin package) &lt;code&gt;com.oneeyedmen.book.Chapter_01_Spike&lt;/code&gt;. Listing all the source in the directory we see&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code&gt;01_a_Spike-Introduction.kt&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;01_b_Spike-First-Kotlin-File.kt&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;01_c_Spike-First-Attempt-at-Publishing.kt&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;01_d_Spike-Combining-Files.kt&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the time it’s taken to write the contents, these filenames have changed several times, with the aim to allow me to see what is in them and at the same time process them automatically. Let’s see if I succeeded in that second goal by processing all the files in sequence.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun main(args: Array&amp;lt;String&amp;gt;) {
    val dir = File(&quot;src/main/java/com/oneeyedmen/book/Chapter_01_Spike&quot;)
    val translatedLines: Sequence&amp;lt;String&amp;gt; = sourceFilesIn(dir)
        .flatMap(this::translate)

    val outDir = File(&quot;build/book&quot;).apply {
        mkdirs()
    }

    outDir.resolve(dir.name + &quot;.md&quot;).bufferedWriter(Charsets.UTF_8).use { writer -&amp;gt;
        translatedLines.forEach {
            writer.appendln(it)
        }
    }
}

fun sourceFilesIn(dir: File) = dir
    .listFiles { file -&amp;gt; file.isSourceFile() }
    .toList()
    .sortedBy(File::getName)
    .asSequence()

private fun File.isSourceFile() = isFile &amp;amp;&amp;amp; !isHidden &amp;amp;&amp;amp; name.endsWith(&quot;.kt&quot;)

fun translate(source: File): Sequence&amp;lt;String&amp;gt; = translate(source.readText(Charsets.UTF_8))

fun translate(sourceLines: String): Sequence&amp;lt;String&amp;gt; {
    var inCodeBlock = false
    var inTextBlock = false
    return sourceLines.splitToSequence(&quot;\n&quot;)
        .map { line -&amp;gt;
            when {
                !inCodeBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = true
                    &quot;```kotlin&quot;
                }
                inCodeBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;//`&quot;) -&amp;gt; {
                    inCodeBlock = false
                    &quot;```&quot;
                }
                !inTextBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;/*-&quot;) -&amp;gt; {
                    inTextBlock = true
                    null
                }
                inTextBlock &amp;amp;&amp;amp; line.firstNonSpaceCharsAre(&quot;-*/&quot;) -&amp;gt; {
                    inTextBlock = false
                    null
                }
                inTextBlock -&amp;gt; line
                inCodeBlock -&amp;gt; line
                else -&amp;gt; null
            }
        }
        .filterNotNull()
}

fun String.firstNonSpaceCharsAre(s: String) = this.trimStart().startsWith(s)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Looking back at the last version of the &lt;code&gt;translate&lt;/code&gt; function you’ll see that I have changed returning a Sequence - this will allow me to avoid having all the text of all files in memory. I’ve also put &lt;code&gt;null&lt;/code&gt;s into that Sequence where we are skipping a line, and then filtered out nulls from the Sequence with &lt;code&gt;filterNotNull&lt;/code&gt;, so that we don’t have a blank line for each source line we aren’t outputting.&lt;/p&gt;

&lt;p&gt;The rest of the code is pretty standard Kotlin - not very pretty or abstracted yet but good enough. It would probably read very much the same if I wrote it in Python - which I would if I didn’t have Kotlin here as it would be just too verbose in Java.&lt;/p&gt;

&lt;p&gt;I had to up update the test as well as the code to account for the change to the signature of &lt;code&gt;translate&lt;/code&gt;. The test is now&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class CodeExtractorTests {

    @Rule @JvmField val approver = approvalsRule()

    @Test fun writes_a_markdown_file_from_Kotlin_file() {
        val source = &quot;&quot;&quot;
        |package should.not.be.shown
        |/*-
        |Title
        |=====
        |This is Markdown paragraph
        |-*/
        |object HiddenContext {
        |  //`
        |  /* This is a code comment
        |  */
        |  fun aFunction() {
        |     return 42
        |  }
        |  //`
        |}
        |/*-
        |More book text.
        |-*/
        &quot;&quot;&quot;.trimMargin()
        approver.assertApproved(translate(source).joinToString(&quot;\n&quot;))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the approved file shows no blank lines where we the skip a line in the source&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;Title
=====
This is Markdown paragraph
```kotlin
  /* This is a code comment
  */
  fun aFunction() {
     return 42
  }
```
More book text.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running the code and looking at the rendered Markdown with IntelliJ’s Markdown plugin I see one glaring problem. Where one file ends and another starts we need to separate them with a blank line if the combined Markdown isn’t to be interpreted as a contiguous paragraph. Let’s fix that by adding a blank line to the end of each file’s lines.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val translatedLines: Sequence&amp;lt;String&amp;gt; = sourceFilesIn(dir)
    .flatMap { translate(it).plus(&quot;\n&quot;) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is one other issue that I can see, which has to do with trying to show in the text how I mark the prose regions. Where I wrote&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;I'm going to go with

⁠/*-
this is book text
⁠-*/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;the markers were interpreted as markers and messed up the output. I add a pipe character &lt;code&gt;|&lt;/code&gt; to the beginning of those marker lines to get things running. I don’t have a solution to this at the moment, bar the pipe, but suspect that we’ll need some way of escaping our own codes. I’m trusting that as I gain fluency with Markdown something clever will come up. If you can see the markers without &lt;code&gt;|&lt;/code&gt;s above I guess I succeeded in the end.&lt;/p&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;What can we learn from this episode?&lt;/p&gt;

&lt;p&gt;Well I learned that this model works for me when actually explaining concepts. Unless you’re viewing the source version of this text, you won’t see that there is a subtlety around the different versions of the code existing in the same source file. When explaining code on my blog I would have to move forward and back between different source versions, cutting and pasting them into the code. Here, I can keep the different versions in the same file, which is a big productivity win.&lt;/p&gt;

&lt;p&gt;My learning that is a demonstration of the big topic - risk reduction. Before I started work on this book I identified the following main risks:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;No-one will want to read what I write on this subject&lt;/li&gt;
  &lt;li&gt;It will be too much effort to maintain a code-heavy text&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These are typical of the 2 major risks facing a new software project - failure in the market and failure to be able to deliver economically (if at all). Unless we are certain that we can build something that our customers will want we had better address both risks early on. The way to address them is by gathering information as quickly and as cheaply as possible.&lt;/p&gt;

&lt;p&gt;If you are reading this text in anything other than the finished book, then you’ll see that I will have addressed the market risk by releasing the product before it was finished in order to gauge if there is any enthusiasm. The chapter itself has been me addressing the technical risk that it’s too hard to write about code by&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Hypothesising that I could write the book text within the source code rather than vice versa, and that that would be an efficient process, if I had a tool to extract it.&lt;/li&gt;
  &lt;li&gt;Experimenting to see if the hypothesis is true by trying it out.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I’ve done just enough here to show that the book-in-comments approach has legs. No doubt I’ll spend days on tooling to produce the book before I’m finished - the code is rough and the inability to write about my own notation without invoking it is a shame - but right now I have confidence without too much cost.&lt;/p&gt;

&lt;p&gt;Tooling is another take-away. Modern developers will go to great lengths to increase their own productivity by building tools to leverage their time. Sometimes these are simple scripts, sometimes full applications. I’m hoping to leverage the power of an IDE that I already know with some text processing to produce something greater than the sum of its parts.&lt;/p&gt;

&lt;p&gt;Leverage is my final thought. Can we find ways of solving several problems at once? In this case I’ve managed to test the writing model, written some tooling to support it, and perhaps demonstrated some aspects of modern programming, all at the same time. We should obviously strive for humility, but I’m secretly a bit pleased with myself.&lt;/p&gt;

&lt;h2 id=&quot;request-for-feedback&quot;&gt;Request for Feedback&lt;/h2&gt;

&lt;p&gt;Well you’ve either got this far, or skipped here having decided that the content wasn’t from you. Could you spare a couple of minutes to help me gauge whether I am wasting my time?&lt;/p&gt;

&lt;p&gt;If so …&lt;/p&gt;

&lt;p&gt;… please create an &lt;a href=&quot;mailto:duncan@oneeyedmen.com?subject=Book%20Feedback&quot;&gt;email to me&lt;/a&gt;, copy the following into an email, start answering at the top, keep going until you don’t think you owe me any more or your precious time, and send. I’m sorry that I don’t have an embedded form or anything - yet. Maybe if there is enough encouragement the processing of the form will become a chapter!&lt;/p&gt;

&lt;blockquote&gt;
  &lt;ol&gt;
    &lt;li&gt;Should I continue writing this book? [y | n]&lt;/li&gt;
    &lt;li&gt;Are you in the book’s target market (3 - 10+ years of programming experience)? [y | n]&lt;/li&gt;
    &lt;li&gt;What do you think of the recursive nature of the material, writing about the development of the software to assist the writing? [0 (disaster) - 10 (triumph)]&lt;/li&gt;
    &lt;li&gt;How likely are you to recommend the book to a friend or colleague? [0 (not at all) - 10 (extremely)]&lt;/li&gt;
    &lt;li&gt;Would you pay to read the completed book? [y | n]&lt;/li&gt;
    &lt;li&gt;Do you care about paper copies of books? [y | n]&lt;/li&gt;
    &lt;li&gt;Is there anything else you’d like to say? [ … ]&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you do like what I’ve written, then there is more available on &lt;a href=&quot;https://leanpub.com/episodes/&quot;&gt;Leanpub&lt;/a&gt; where you can read the other chapters for free. And please invite a friend.&lt;/p&gt;

&lt;p&gt;Thank you&lt;/p&gt;

&lt;p&gt;Duncan&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Objects and Functions in Kotlin - Part 2</title>
   <link href="http://0.0.0.0:4000/objects-and-functions-in-kotlin-part2.html"/>
   <updated>2017-05-17T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/objects-and-functions-in-kotlin-part2</id>
   <content type="html">&lt;p&gt;In &lt;a href=&quot;objects-and-functions-in-kotlin-part1.html&quot;&gt;Part 1&lt;/a&gt; we started looking at the issue of encapsulating configuration information in object and functional styles. In this second part I’ll continue the exploration before looking at expressing differences in behaviour.&lt;/p&gt;

&lt;p&gt;Let’s first refactor the two previous solutions to look even more similar by adding a static &lt;code&gt;createEmailSender&lt;/code&gt; function to invoke the OO constructor.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun send(
    email: Email,
    serverAddress: InetAddress,
    username: String,
    password: String) {
    TODO()
}

object OOContext {

    interface ISendEmail {
        fun send(email: Email): Unit
    }

    class EmailSender(
        val serverAddress: InetAddress,
        val username: String,
        val password: String
    ) : ISendEmail {
        override fun send(email: Email) =
            send(email, serverAddress, username, password)
    }

    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): ISendEmail = EmailSender(serverAddress, username, password)
}

object FPContext {
    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): (Email) -&amp;gt; Unit =
        { message -&amp;gt;
            send(message, serverAddress, username, password)
        }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The OO solution is quite a bit more wordy than the functional one, but that is because it has defined two new types, whereas the functional version has just reused a function type. Both are implemented as manual &lt;a href=&quot;https://en.wikipedia.org/wiki/Partial_application&quot;&gt;partial application&lt;/a&gt; of the &lt;code&gt;send(email, serverAddress, username, password)&lt;/code&gt; function. In use the two methods are virtually identical:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object OOCaller {

    val sender: ISendEmail = OOContext.createEmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun sendDistress(sender: ISendEmail) {
        sender.send(Email(&quot;kenobi@rebelalliance.org&quot;, &quot;Help me&quot;, &quot;...&quot;))
    }

    fun onUnderAttack() {
        sendDistress(sender)
    }
}

object FPCaller {

    val sender: (Email) -&amp;gt; Unit = FPContext.createEmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun sendDistress(sender: (Email) -&amp;gt; Unit) {
        sender(Email(&quot;kenobi@rebelalliance.org&quot;, &quot;Help me&quot;, &quot;...&quot;))
    }

    fun onUnderAttack() {
        sendDistress(sender)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The only visible differences are the types of the senders and the fact that we have to call &lt;code&gt;ooSender.send(...)&lt;/code&gt; where we just invoke &lt;code&gt;fpSender(...)&lt;/code&gt;. The latter is in fact syntactic sugar for &lt;code&gt;fpSender.invoke(...)&lt;/code&gt;, so this latter difference really just comes down to the name of the method called.&lt;/p&gt;

&lt;p&gt;This points to a mapping between a function and an object that has a single method with the same signature. Or, put another way, between the function type and a single method interface. This similarity is at the heart of Java 8’s functional programming facilities. Java doesn’t have a syntax for function signatures, so it substitutes interfaces with a single method of the signature that it would like to express.&lt;/p&gt;

&lt;p&gt;The same is true for Kotlin, which although it does have a function signature syntax, also defines interfaces that are the equivalent. So in Kotlin, where &lt;code&gt;Function1&amp;lt;P, R&amp;gt;&lt;/code&gt; is magicked into existence by the compiler, we could write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun sendDistress(sender: Function1&amp;lt;Email, Unit&amp;gt;) {
        sender(Email(&quot;kenobi@rebelalliance.org&quot;, &quot;Help me&quot;, &quot;...&quot;))
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I won’t mention this again, as the &lt;code&gt;(Email) -&amp;gt; Unit&lt;/code&gt; syntax prevails, but every now and again IntelliJ will introduce the Function types as part of a refactoring, so it’s best to be prepared.&lt;/p&gt;

&lt;p&gt;Can we bring our OO and FP solutions even closer together? Why yes we can. Because the function type is just an interface, &lt;code&gt;EmailSender&lt;/code&gt; can implement it. How? By defining a method &lt;code&gt;invoke&lt;/code&gt; with the signature of the function type.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object OOContext2 {

    class EmailSender(
        val serverAddress: InetAddress,
        val username: String,
        val password: String
    ) : ISendEmail, (Email) -&amp;gt; Unit {

        override fun send(email: Email) =
            send(email, serverAddress, username, password)

        override fun invoke(email: Email) = send(email)

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we do this then we can use our class-based sender in place of our functional one.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object MixedCalling {

    val sender: (Email) -&amp;gt; Unit = OOContext2.EmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun onUnderAttack() {
        FPCaller.sendDistress(sender)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now our OO solution has become quite a bit more complicated in order to fit in with the FP approach. This calls into question the usefulness of our &lt;code&gt;ISendEmail&lt;/code&gt; interface. We can see that it is equivalent to the function type &lt;code&gt;(Email) -&amp;gt; Unit&lt;/code&gt; - all it does is give the name &lt;code&gt;send&lt;/code&gt; to what happens when you invoke it. Maybe we could just use the type &lt;code&gt;(Email) -&amp;gt; Unit&lt;/code&gt; everywhere in place of &lt;code&gt;ISendEmail&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;If you think that might not be expressive enough, then maybe you aren’t a functional programmer. Luckily there is a middle ground - we can use a typealias to give a name to the functional type, thus communicating our intent.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;typealias ISendEmailToo = (Email) -&amp;gt; Unit

object OOContext3 {

    class EmailSender(
        val serverAddress: InetAddress,
        val username: String,
        val password: String
    ) : ISendEmailToo {

        override fun invoke(email: Email) =
            send(email, serverAddress, username, password)
    }

    val sender: ISendEmailToo = EmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun onUnderAttack() {
        FPCaller.sendDistress(sender)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that as the typealias is just an alias - it doesn’t define a new type - you can write &lt;code&gt;ISendEmailToo&lt;/code&gt; and &lt;code&gt;(Email) -&amp;gt; Unit&lt;/code&gt; interchangeably, so that &lt;code&gt;FPCalling.sendDistress&lt;/code&gt; doesn’t have to be retrofitted with the typealias in order to be called.&lt;/p&gt;

&lt;p&gt;There is another way of bridging the OO FP gap that doesn’t involve making your classes implement function types - create a function at the point of invocation. Given our old class-based solution:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;object OOContext4 {

    class EmailSender(
        val serverAddress: InetAddress,
        val username: String,
        val password: String
    ) {
        fun send(email: Email) =
            send(email, serverAddress, username, password)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;we could create a lambda to pass to our functional code&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    val sender = OOContext4.EmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun onUnderAttack() {
        FPCaller.sendDistress { sender.send(it) }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;or just pass a method reference&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun onUnderAttack() {
        FPCaller.sendDistress(sender::send)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Can we do the opposite - pass our functional sender into something that expects an &lt;code&gt;ISendEmail&lt;/code&gt;? Unless I’ve missed a trick; that requires more ceremony, at least in Kotlin, as we have to create an anonymous object implementing &lt;code&gt;ISendEmail&lt;/code&gt; to perform the thunk.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    val sender: (Email) -&amp;gt; Unit = FPContext.createEmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun onUnderAttack() {
        OOCaller.sendDistress(object: ISendEmail {
            override fun send(email: Email) = sender(email)
        })
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Seeing an anonymous implementation of an interface reminds me that we could have implemented an OO solution without introducing a named class.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): ISendEmail =
        object : ISendEmail {
            override fun send(email: Email) = send(email, serverAddress, username, password)
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the unlikely event that you’ve made it this far, you may be wondering when to use which method. The fundamental question is, I suppose, should your primary interface for expressing email sending be the &lt;code&gt;ISendEmail&lt;/code&gt; interface, which helpfully names its single method, or the &lt;code&gt;ISendEmailToo&lt;/code&gt; typealias or its equivalent &lt;code&gt;(Email) -&amp;gt; Unit&lt;/code&gt;, which is itself an alias for the generic interface &lt;code&gt;Function1&amp;lt;Email, Unit&amp;gt;&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;That last statement gives a clue that at the generated bytecode level things are going to be much the same - the compiler is going to be generating implementations of either interface if we don’t.&lt;/p&gt;

&lt;p&gt;If you’re a Kotlin programmer and have to interoperate with Java, then I’d tend to define ISendEmail, as otherwise you’ll be exposing Kotlin function types to your callers’ Java code.&lt;/p&gt;

&lt;p&gt;Otherwise my recent practice has been to define the type of parameters or properties as the function type where I can, providing a typealias where required to fully communicate intent. This allows me to provide implementations as either:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Classes that implement the function type&lt;/li&gt;
  &lt;li&gt;Functional partial application&lt;/li&gt;
  &lt;li&gt;Ad-hoc lambdas&lt;/li&gt;
  &lt;li&gt;References to methods with the same signature&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I’ve come to consider the functional types as a kind of duck-typing - because they’re built-in to the language you can substitute objects without having to rely on a specific shared type - passing a method reference where a Ruby programmer might pass an object with a known method name.&lt;/p&gt;

&lt;p&gt;Of course this only applies where we are talking about interfaces that can be expressed by only one function. Where we want to delegate several operations we could pass multiple functions, but by this stage an actual interface with named methods is probably on the cards. It is surprising though just how often you can express a dependency with a function type, and how expressive and flexible they can make your code.&lt;/p&gt;

&lt;p&gt;Stay tuned for Part 3, where I’ll look at another way that objects and functions solve the same problem in different ways.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Objects and Functions in Kotlin - Part 1</title>
   <link href="http://0.0.0.0:4000/objects-and-functions-in-kotlin-part1.html"/>
   <updated>2017-05-17T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/objects-and-functions-in-kotlin-part1</id>
   <content type="html">&lt;p&gt;Imagine, if you can, that you need to send email from some code that you are writing. Just that - not receive mail, or list sent messages - just fire and forget.&lt;/p&gt;

&lt;p&gt;As a user of this facility, I’d like to call a function, passing it the information in the email. So given a representation of an email&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class Email(
    val to: String,
    val subject: String,
    val body: String
)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;then I’d like to invoke a function like&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun send(email: Email) {
    TODO()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course when I come to implement this function, I discover that all sorts of other information is required to &lt;em&gt;actually&lt;/em&gt; send email. This isn’t information about the email itself, but rather configuration about how to send it. Things like the sending email server’s IP address, login details, other security credentials, timeouts, senders email address - all the things that most people don’t know but you need to set up their new computer. Given the multitude of different email systems, in the end API’s like &lt;a href=&quot;https://javamail.java.net/nonav/docs/api/&quot;&gt;JavaMail&lt;/a&gt; basically punt and pass a whole dictionary, but for now, let’s let 3 parameters stand in for the lot.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun send(
    email: Email,
    serverAddress: InetAddress,
    username: String,
    password: String) {
    TODO()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As a client things have just gotten a lot less convenient. Everywhere I want to send email has to know about this petty configuration - I’ll be passing it around from the top to the bottom of my codebase. I solve that problem by putting it into global variables which works fine until I discover that every run of my unit test suite now ends up sending 5 emails! There must be a better way of hiding these petty details.&lt;/p&gt;

&lt;p&gt;You’re probably an object-oriented programmer, so you have a ready-made solution to this problem.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    class EmailSender(
        val serverAddress: InetAddress,
        val username: String,
        val password: String
    ) {
        fun send(email: Email) {
            TODO()
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now when I want to send email I need access to an EmailSender (which I also have to pass around). Instead of calling a function, we invoke a method. We tell it to send, and we don’t have to tell it the petty details it needs because it already knows.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    val sender = EmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun sendDistress(sender: EmailSender) {
        sender.send(Email(&quot;kenobi@rebelalliance.org&quot;, &quot;Help me&quot;, &quot;...&quot;))
    }

    fun onUnderAttack() {
        sendDistress(sender)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As a bonus, if I extract an interface, I can configure my tests to use a dummy and not actually send emails.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    interface ISendEmail {
        fun send(email: Email): Unit
    }

    class EmailSender(
        val serverAddress: InetAddress,
        val username: String,
        val password: String
    ) : ISendEmail {
        override fun send(email: Email) {
            TODO()
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that this is not implementation hiding. The static function hides the details of how to connect to a server and send email. Here we are just hiding configuration. Granted we can see that the OO approach could lead to &lt;code&gt;SmtpEmailSender&lt;/code&gt; and &lt;code&gt;X400EmailSender&lt;/code&gt; implementations, but we aren’t at that stage yet.&lt;/p&gt;

&lt;p&gt;How would a functional programmer solve the same problem?&lt;/p&gt;

&lt;p&gt;Remember that we’re trying to get to a function with this signature&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun sendMessage(email: Email) {
        TODO()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;given an implementation that looks like this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun sendMessage(
        email: Email,
        serverAddress: InetAddress,
        username: String,
        password: String) {
        TODO()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is &lt;a href=&quot;https://en.wikipedia.org/wiki/Partial_application&quot;&gt;partial application&lt;/a&gt; - fixing a number of arguments to a function to give a function with fewer arguments. While some languages provide built-in support for this sort of thing, in Kotlin the easiest approach is to write a function to partially apply our configuration.&lt;/p&gt;

&lt;p&gt;What we want is a function that takes the configuration, and returns a function that knows how to send a message.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): (Email) -&amp;gt; Unit {
        TODO()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the functional analog of the OO case, where the &lt;code&gt;EmailSender&lt;/code&gt; constructor is a function that ‘returns’ an object that knows how to send a message.&lt;/p&gt;

&lt;p&gt;In longhand, our function can return an inner function that captures the arguments it requires from the parent&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): (Email) -&amp;gt; Unit {

        fun result(email: Email) {
            send(email, serverAddress, username, password)
        }

        return ::result
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can then make the return a lamba expression&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): (Email) -&amp;gt; Unit {

        val result: (Email) -&amp;gt; Unit = { message -&amp;gt; send(message, serverAddress, username, password) }

        return result
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;before inlining all the stuff to leave this functional definition&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    fun createEmailSender(
        serverAddress: InetAddress,
        username: String,
        password: String): (Email) -&amp;gt; Unit =
        { message -&amp;gt;
            send(message, serverAddress, username, password)
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;ie &lt;code&gt;createMessageSender&lt;/code&gt; is a function that returns a lamba that calls &lt;code&gt;sendMessage&lt;/code&gt; combining the lambda’s single message argument with the configuration from &lt;code&gt;createMessageSender&lt;/code&gt;. This lambda is also known as a &lt;em&gt;closure&lt;/em&gt;, as it closes-over the values that it requires from it’s enclosing context, capturing them for use later.&lt;/p&gt;

&lt;p&gt;To use this function, we can create it in one place and invoke it in another, very much as we did with the object solution.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;    val sender: (Email) -&amp;gt; Unit = createEmailSender(inetAddress(&quot;smtp.rebelalliance.org&quot;), &quot;username&quot;, &quot;password&quot;)

    fun sendDistress(sender: (Email) -&amp;gt; Unit) {
        sender(Email(&quot;kenobi@rebelalliance.org&quot;, &quot;Help me&quot;, &quot;...&quot;))
    }

    fun onUnderAttack() {
        sendDistress(sender)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That concludes Part I. If you’re an OO programmer who hasn’t been exposed to functional techniques, I suspect that it has been hard to follow. If you can though, stick with it, as you do get used to the style, and it does allow us to solve problems and express our intent in new and interesting ways.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;objects-and-functions-in-kotlin-part2.html&quot;&gt;Part 2&lt;/a&gt; I’ll look at ways in which we can interoperate between the object and functional worlds.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Test Driven Development v Testing Part 3 - Approval Tests</title>
   <link href="http://0.0.0.0:4000/tdd-v-testing-part3.html"/>
   <updated>2017-01-21T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/tdd-v-testing-part3</id>
   <content type="html">&lt;p&gt;This isn’t the post I thought I was going to write for Part 3 &lt;a href=&quot;/tdd-v-testing-part2.html&quot;&gt;last week&lt;/a&gt;, but it occurred to me that I could reasonably TDD FizzBuzz with &lt;a href=&quot;http://approvaltests.com/&quot;&gt;Approval Tests&lt;/a&gt; too, so here goes.&lt;/p&gt;

&lt;p&gt;Approval Testing is basically the application of Golden Master Testing to in-development rather than legacy code. You really don’t need any test infrastructure to do this, but as I wrote some, we’re going to use it!&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/dmcg/okey-doke&quot;&gt;Okey-doke&lt;/a&gt; is a library that integrates with JUnit via a Rule.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;public class FizzBuzzApprovalsTests {    
    @Rule public ApprovalsRule approver = ApprovalsRule.usualRule(); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The nature of Approval Testing is that we just write code and approve its output if it meets our expectations. So let’s add a test using the approver and see what happens.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test
    public void test() {
        approver.assertApproved(fizzBuzz(1));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nothing can happen until the code compiles, and approvals testing is all about moving fast, so let’s just add an implementation that covers most cases.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running this gives a test failure&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;java.lang.AssertionError: 
Expected :null
Actual   :1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is telling us that nothing was expected (there is not yet any approved output for this test). A file &lt;code&gt;FizzBuzzApprovalsTests.test.actual&lt;/code&gt; is created with the actual output, viz&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Okeydoke also tells you what to do if you want to do to approve the output&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;To approve...
cp '/Users/duncan/Documents/Work/website-jekyll/site/FizzBuzz/src/com/oneeyedmen/play/FizzBuzzApprovalsTests.test.actual' '/Users/duncan/Documents/Work/website-jekyll/site/FizzBuzz/src/com/oneeyedmen/play/FizzBuzzApprovalsTests.test.approved'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Do we want to approve? Well, the output of &lt;code&gt;1&lt;/code&gt; is right for the case we’ve considered, so let’s copy the actual to the approved file as suggested and run the tests again. This time they pass as they are the same. We could add the &lt;code&gt;FizzBuzzApprovalsTests.test.approved&lt;/code&gt; to version control as it is effectively part of our test sources.&lt;/p&gt;

&lt;p&gt;Now we could write another test to cover other numbers, but with Approval Tests it’s easy to check a lot of cases at once, so let’s check 1 … 31 by building a string with the results and checking that&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test
    public void test() {
        approver.assertApproved(
            IntStream.range(1, 32).mapToObj(this::fizzBuzz).collect(joining(&quot;,&quot;))
        );
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which fails&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;org.junit.ComparisonFailure: 
Expected :1
Actual   :1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but it is what we want so we approve it, and run the tests again just to make sure they pass now.&lt;/p&gt;

&lt;p&gt;Now instead of writing another test we can just add to our implementation.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and run the test&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;org.junit.ComparisonFailure: 
Expected :1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
Actual   :1,2,Fizz,4,5,Fizz,7,8,Fizz,10,11,Fizz,13,14,Fizz,16,17,Fizz,19,20,Fizz,22,23,Fizz,25,26,Fizz,28,29,Fizz,31
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmmm, it’s getting difficult to see what’s going on there, as the expected and actual are out of sync on the line. As this is deliberate practice, I’m going to stash the production change and fix the output format first.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;IntStream.range(1, 32).mapToObj(this::fizzBuzz).collect(joining(&quot;\n&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running the test this time we can’t see a diff in the console, but crucially IntelliJ says&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;org.junit.ComparisonFailure:  &amp;lt;Click to see difference&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Clicking to see the difference gives us a diff view showing something like&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Expected                    Actual
1,2,3,4,5,6,7,8,9,10,11..   1 
                            2 
                            3 
                            4 
...                        
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which was the point of the formatting change, so we approve, then unstash the production change to give a failing test with the diff&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Expected                    Actual       
1                           1
2                           2
3                           Fizz
4                           4
5                           5
6                           Fizz
7                           7
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is going to let us make a lot more sense of the results. So we approve, and then write more production code.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This causes another approvals failure&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Expected                    Actual
1                           1
2                           2
Fizz                        Fizz
4                           4
5                           Buzz
Fizz                        Fizz
7                           7
8                           8
Fizz                        Fizz
10                          Buzz
11                          11
Fizz                        Fizz
13                          13
14                          14
Fizz                        Fizz
16                          16
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is closer, so we approve that too. One last step&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        if (i % 15 == 0) return &quot;FizzBuzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and we run the tests, which pass. A quick check-in, and we’re home in time for tea and medals.&lt;/p&gt;

&lt;p&gt;Luckily my pair, maybe it was you, points out that they shouldn’t have passed, as the approved file still shows Fizz at 15 rather than FizzBuzz. Complacency is the main problem I have with Approval tests, but luckily we hadn’t pushed, so our embarrassment is local. A quick fix&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 15 == 0) return &quot;FizzBuzz&quot;;
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;gives the desired change&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Expected                    Actual
1                           1
2                           2
Fizz                        Fizz
4                           4
5                           Buzz
Fizz                        Fizz
7                           7
8                           8
Fizz                        Fizz
10                          Buzz
11                          11
Fizz                        Fizz
13                          13
14                          14
Fizz                        FizzBuzz
16                          16
17                          17
Fizz                        Fizz
19                          19
20                          Buzz
Fizz                        Fizz
22                          22
23                          23
Fizz                        Fizz
25                          Buzz
26                          26
Fizz                        Fizz
28                          28
29                          29
Fizz                        FizzBuzz
31                          31
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which we approve and then amend commit. I think we got away with it.&lt;/p&gt;

&lt;p&gt;Compared to the example-based tests in &lt;a href=&quot;/tdd-v-testing-part1.html&quot;&gt;Part 1&lt;/a&gt;, or the theories of &lt;a href=&quot;/tdd-v-testing-part2.html&quot;&gt;Part 2&lt;/a&gt;, our final test is very simple&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test
    public void test() {
        approver.assertApproved(
            IntStream.range(1, 32).mapToObj(this::fizzBuzz).collect(joining(&quot;\n&quot;))
        );
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In fact it makes no sense until you look into &lt;code&gt;FizzBuzzApprovalsTests.test.approved&lt;/code&gt; and see&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Does this make enough sense, given that we have to read it separately from the test? Maybe not, especially given that my previous encouragement to make tests more communicative after the TDD. Let’s finish by making that approved file more explicit&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;IntStream.range(1, 32).mapToObj((i) -&amp;gt;  i + &quot;\t = \t&quot; + fizzBuzz(i)).collect(joining(&quot;\n&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;pre&gt;&lt;code&gt;1	 = 	1
2	 = 	2
3	 = 	Fizz
4	 = 	4
5	 = 	Buzz
6	 = 	Fizz
7	 = 	7
8	 = 	8
9	 = 	Fizz
10	 = 	Buzz
11	 = 	11
12	 = 	Fizz
13	 = 	13
14	 = 	14
15	 = 	FizzBuzz
16	 = 	16
17	 = 	17
18	 = 	Fizz
19	 = 	19
20	 = 	Buzz
21	 = 	Fizz
22	 = 	22
23	 = 	23
24	 = 	Fizz
25	 = 	Buzz
26	 = 	26
27	 = 	Fizz
28	 = 	28
29	 = 	29
30	 = 	FizzBuzz
31	 = 	31
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once you’re in the flow with Approval tests they can be very productive, especially when you don’t need the help of writing a test to work out what the next step is. I suppose we’re skipping the test driving and going straight to the proof-against-regression bit of testing. They are also splendid for getting existing code without tests under test quickly and cheaply, although I suppose that is just Golden Master Testing.&lt;/p&gt;

&lt;p&gt;The main downside is that we can’t look directly in the test to see examples of what the code does - we have to look in the approved file. Those examples may also fail to be good documentation to allow us to understand what the code does - in this case they’d do for another programmer, but not for an 8 year-old. Or maybe vice-versa, I’m often wrong.&lt;/p&gt;

&lt;p&gt;One application where they really do shine is where we are incrementally improving an algorithm and stopping when it is good enough. This time last year I was parsing a list of strings into first name, given name, title etc. Given a corpus of 2000 names I could approve each improvement and know when a change had led to better or worse results very quickly. Example-based tests would have become unwieldy very quickly in comparison. They can be also be a cheap warning when other things have changed too - I once wrote an Approval Test for the contents of our deployed lib directory so that we didn’t accidentally upgrade dependencies when making changes to the unfathomable Maven build.&lt;/p&gt;

&lt;p&gt;I still think that there’s another post to come in this series. I’ll let you know on &lt;a href=&quot;https://twitter.com/duncanmcg&quot;&gt;Twitter&lt;/a&gt; when it arrives.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Test Driven Development v Testing Part 2 - Theory Tests</title>
   <link href="http://0.0.0.0:4000/tdd-v-testing-part2.html"/>
   <updated>2017-01-15T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/tdd-v-testing-part2</id>
   <content type="html">&lt;p&gt;As promised at the end of &lt;a href=&quot;/tdd-v-testing-part1.html&quot;&gt;Part 1&lt;/a&gt;, I’ll now go through the steps of TDDing FizzBuzz with JUnit theories, inspired by Dominic Fox’s excellent post titled &lt;a href=&quot;https://opencredo.com/tdd-fizzbuzz-junit-theories/&quot;&gt;How to TDD FizzBuzz with JUnit Theories&lt;/a&gt;. My reasons for doing this are&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;To compare theories with the ‘traditional’ example-based process shown in Part 1.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Because informative though Dominic’s post was, it didn’t actually show any TDD, just some tests that may or may not have been the end result of some test driving.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;To better understand JUnit theories myself.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, let’s go.&lt;/p&gt;

&lt;p&gt;There is more scaffolding and less IntelliJ handholding when writing a JUnit theory test, but I guess we’ll get used to it. Actually I’m just going to copy Dominic’s setup, but using 31 as the upper bound of the values that we’re going to check, as anything more is just a waste.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@RunWith(Theories.class)
public class FizzBuzzTheoryTests {
    @DataPoints
    public static final int[] numbers = IntStream.range(1, 31).toArray();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now what is our first test? In Part 1 this was easy, we just had to assert something about the result for number &lt;code&gt;1&lt;/code&gt;.  With theories it’s harder, because we have to assert something that is true for all numbers, will drive our implementation, and allows us to make a very small change. The best I can come up with is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void is_not_null(int i) {
        assertNotNull(fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is at least uncontentious and, through its failure to compile, makes us add our first line of implementation.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        return &quot;&quot;;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This passes straight away, so we can add another theory to drive more code.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void is_string_of_number(int i) {
        assertEquals(Integer.valueOf(i), fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I must say that this step left me feeling a bit icky. Firstly, we have done exactly what Dominic complained about in his article - defined the code to be written in the test. I suppose that we could find another expression of the same thing, &lt;code&gt;&quot;&quot; + i&lt;/code&gt; maybe. Or taken Dominic’s approach and just specified that the result should have only digits, at the expense of under-specifying. Let’s just say that this is a toy example, for real code there may be a way of specifying the result that is less complicated than the production code.&lt;/p&gt;

&lt;p&gt;Also, we’ve written something that we know is not going to be true later on - this test is only going to be valid for a subset of the ints. We could fix that now, but my inner pair is eager to see a green bar, so we go ahead and write the code&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which passes, and then go back and retrofit the assumption.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void is_string_of_number_for_other_numbers(int i) {
        assumeTrue(i % 3 != 0 &amp;amp;&amp;amp; i % 5 != 0);
        assertEquals(String.valueOf(i), fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which continues to pass. Now for 3’s&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void is_fizz_when_divisible_by_3(int i) {
        assumeTrue(i % 3 == 0);
        assertEquals(&quot;Fizz&quot;, fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;leading to&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and 5’s&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void is_buzz_when_divisible_by_5(int i) {
        assumeTrue(i % 5 == 0);
        assertEquals(&quot;Buzz&quot;, fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;leading to&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which still fails!&lt;/p&gt;

&lt;p&gt;Now this is the interesting part of the theories TDD. At this stage in Part 2 we had to add a test ourselves to drive out the case of numbers divisible by 15. This time, our naive implementation fails the is_buzz_when_divisible_by_5 test in this case. So a point to the more formal specification, but now we have a few things to do to get to a passing case.&lt;/p&gt;

&lt;p&gt;We can try just fixing the code&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 15 == 0) return &quot;FizzBuzz&quot;;
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but that leads to 2 broken tests! As this is deliberate practice, we should probably back out the production change and fix the tests first, Mikado-style.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void starts_with_fizz_when_divisible_by_3(int i) {
        assumeTrue(i % 3 == 0);
        assertTrue(fizzBuzz(i).matches(&quot;Fizz.*&quot;));
    }

    @Theory
    public void ends_with_buzz_when_divisible_by_5(int i) {
        assumeTrue(i % 5 == 0);
        assertTrue(fizzBuzz(i).matches(&quot;.*Buzz&quot;));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My internal pair and I had a long discussion over this. Should we test for the simple contains, or starts/ends with? In the end we plumped for the start and end, as I felt that they expressed the problem better. The tests are still broken of course, and for longer than he was comfortable with, but at least we know the fix is easy.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 15 == 0) return &quot;FizzBuzz&quot;;
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Phew. Are we done? I’m pretty sure that &lt;code&gt;is_not_null&lt;/code&gt; is now superfluous, so deleting that and reordering to tell a story we have&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void starts_with_fizz_when_divisible_by_3(int i) {
        assumeTrue(i % 3 == 0);
        assertTrue(fizzBuzz(i).matches(&quot;Fizz.*&quot;));
    }

    @Theory
    public void ends_with_buzz_when_divisible_by_5(int i) {
        assumeTrue(i % 5 == 0);
        assertTrue(fizzBuzz(i).matches(&quot;.*Buzz&quot;));
    }

    @Theory
    public void is_string_of_number_for_other_numbers(int i) {
        assumeTrue(i % 3 != 0 &amp;amp;&amp;amp; i % 5 != 0);
        assertEquals(String.valueOf(i), fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By the standards of Part 1, then I think that yes, we are done. Our tests will guard against regression, they make good documentation; they might be broken by a determined editor. Personally, they feel a little unfinished though. Perhaps because of their formality, you realise that they don’t fully specify the behaviour - you couldn’t re-implement the code given the test because nothing actually specifies what &lt;code&gt;fizzBuzz(15)&lt;/code&gt; should return. So I’d end up adding&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Theory
    public void is_fizzbuzz_when_divisible_by_15(int i) {
        assumeTrue(i % 15 == 0);
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(i));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which seems a bit arbitrary, but every other formulation ended up worse. Dominic had a different set of theories, but his also suffer from not actually allowing you to re-implement the code from the spec.&lt;/p&gt;

&lt;p&gt;Let’s remind ourselves what the tests from Part 1 looked like.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void fizz_for_multiples_of_three() {
        assertEquals(&quot;Fizz&quot;, fizzBuzz(3));
        assertEquals(&quot;Fizz&quot;, fizzBuzz(6));
    }

    @Test public void buzz_for_multiples_of_five() {
        assertEquals(&quot;Buzz&quot;, fizzBuzz(5));
        assertEquals(&quot;Buzz&quot;, fizzBuzz(10));
    }

    @Test public void fizzbuzz_for_multiples_of_three_and_five() {
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(15));
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(30));
    }

   @Test public void test_other_numbers() {
        assertEquals(&quot;1&quot;, fizzBuzz(1));
        assertEquals(&quot;2&quot;, fizzBuzz(2));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What have we learnt? For me, TDDing with theories was a lot less comfortable than TDDing with examples, but then I have a lot more experience with the former. In this case I’m not convinced that either my theories or Dominic’s are better tests than the example tests, but they do appeal to the mathematical side of me. Comparing them you can see that the previous tests were a bit sloppy, in particular we should have had names like &lt;code&gt;fizz_for_multiples_of_three_that_arent_also_multiples_of_five&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Which tests better express the rules of FizzBuzz? I think that humans probably value examples over formality, and mathematicians vice versa, so perhaps it depends which way you lean. To me the theories feel like I need to read between the lines, to infer behaviour that should be evident, but maybe I’m just bad at writing them.&lt;/p&gt;

&lt;p&gt;I can better imagine writing theories after the TDD cycle, to better specify and catch regressions. Some algorithms and data structures would benefit from theories to verify that pre and post conditions apply during their TDD. I suppose I’d like to think that any concurrent data structures I use were specified and tested in this mathematical style, but perhaps documented with example tests.&lt;/p&gt;

&lt;p&gt;If you like this post, or even if you don’t, then you should read Nat Pryce’s &lt;a href=&quot;http://natpryce.com/articles/000807.html&quot;&gt;article&lt;/a&gt; about using property tests, closely related to JUnit Theories, to TDD another old favourite, the Diamond Kata.&lt;/p&gt;

&lt;p&gt;And re-reading Dominic’s post in the light of my trying the theories, I think that there is a &lt;a href=&quot;/tdd-v-testing-part3.html&quot;&gt;Part 3&lt;/a&gt; of this series coming, so follow me on &lt;a href=&quot;https://twitter.com/duncanmcg&quot;&gt;Twitter&lt;/a&gt; if you want to know when it is published.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Test Driven Development v Testing Part 1 - Example Tests</title>
   <link href="http://0.0.0.0:4000/tdd-v-testing-part1.html"/>
   <updated>2017-01-14T00:00:00-06:00</updated>
   <id>http://0.0.0.0:4000/tdd-v-testing-part1</id>
   <content type="html">&lt;p&gt;Dominic Fox wrote a very good post recently titled &lt;a href=&quot;https://opencredo.com/tdd-fizzbuzz-junit-theories/&quot;&gt;How to TDD FizzBuzz with JUnit Theories&lt;/a&gt;. In it he wrote &lt;em&gt;“For a long time I was of the opinion that a) FizzBuzz couldn’t be meaningfully TDD’d, and b) this illustrated a common pitfall with TDD.”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As it happens I attended an excellent workshop led by Jon Jagger at &lt;a href=&quot;http://xp2016.org/cfp/Agenda.html#PC5T&quot;&gt;XP2016&lt;/a&gt;. We test-drove FizzBuzz several times as different pairs, coming up with different approaches to the testing and the solution.&lt;/p&gt;

&lt;p&gt;A typical session went something like this.&lt;/p&gt;

&lt;p&gt;First write a test.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void test() {
        assertEquals(&quot;1&quot;, fizzBuzz(1));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That doesn’t compile, so let’s add the function.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        return null;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That fails, so let’s add the simplest implementation.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        return &quot;1&quot;;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This succeeds, but seems like cheating. Let’s write a test to prove it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void test() {
        assertEquals(&quot;1&quot;, fizzBuzz(1));
        assertEquals(&quot;2&quot;, fizzBuzz(2));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That fails, so we can write some production code,&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and maybe rename the test.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void test_other_numbers() {
        assertEquals(&quot;1&quot;, fizzBuzz(1));
        assertEquals(&quot;2&quot;, fizzBuzz(2));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;OK, now for Fizz. Baby steps - this is deliberate practice.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void fizz() {
        assertEquals(&quot;Fizz&quot;, fizzBuzz(3));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Fix the failing test with the simplest fix.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i == 3) return &quot;Fizz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Call the cheating by adding a breaking assertion,&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void fizz_for_multiples_of_three() {
        assertEquals(&quot;Fizz&quot;, fizzBuzz(3));
        assertEquals(&quot;Fizz&quot;, fizzBuzz(6));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which we can then fix.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Buzz now. Let’s take 2 steps forward this time -&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void buzz_for_multiples_of_fice() {
        assertEquals(&quot;Buzz&quot;, fizzBuzz(5));
        assertEquals(&quot;Buzz&quot;, fizzBuzz(10));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which fails, and we’ll go straight to the complicated implementation.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now there’s just one lingering doubt in the back of our minds that we can explore with a test, viz&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test public void fizzbuzz_for_multiples_of_three_and_five() {
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(15));
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(30));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The simplest fix is probably this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        if (i % 15 == 0) return &quot;FizzBuzz&quot;;
        if (i % 3 == 0) return &quot;Fizz&quot;;
        if (i % 5 == 0) return &quot;Buzz&quot;;
        return String.valueOf(i);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;but personally I think that this is a better, if less efficient, expression of the intent&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    public String fizzBuzz(int i) {
        String result = &quot;&quot;;
        if (i % 3 == 0) result = result + &quot;Fizz&quot;;
        if (i % 5 == 0) result = result + &quot;Buzz&quot;;
        return result == &quot;&quot; ? String.valueOf(i) : result;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and yes, I am being deliberately provocative with the &lt;code&gt;==&lt;/code&gt; ;-)&lt;/p&gt;

&lt;p&gt;Let’s have a look at those tests all together.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;   @Test public void test_other_numbers() {
        assertEquals(&quot;1&quot;, fizzBuzz(1));
        assertEquals(&quot;2&quot;, fizzBuzz(2));
    }

    @Test public void fizz_for_multiples_of_three() {
        assertEquals(&quot;Fizz&quot;, fizzBuzz(3));
        assertEquals(&quot;Fizz&quot;, fizzBuzz(6));
    }

    @Test public void buzz_for_multiples_of_five() {
        assertEquals(&quot;Buzz&quot;, fizzBuzz(5));
        assertEquals(&quot;Buzz&quot;, fizzBuzz(10));
    }

    @Test public void fizzbuzz_for_multiples_of_three_and_five() {
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(15));
        assertEquals(&quot;FizzBuzz&quot;, fizzBuzz(30));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and compare them to those that Dominic said &lt;em&gt;“contain the logic of the implementation, only in an obscure and intractable form.”&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test
    public void multiplesOfThreeButNotFiveAreFizz() {
        for (int i = 1; i &amp;lt;= 100; i++) {
            if ((i % 3 == 0) &amp;amp;&amp;amp; !(i % 5 == 0)) {
                assertEquals(&quot;Fizz&quot;, unit.apply(i));
            }
        }
    }
     
    @Test
    public void multiplesOfFiveButNotThreeAreBuzz() {
        for (int i = 1; i &amp;lt;= 100; i++) {
            if (!(i % 3 == 0) &amp;amp;&amp;amp; (i % 5 == 0)) {
                assertEquals(&quot;Buzz&quot;, unit.apply(i));
            }
        }
    }
     
    public void multiplesOfThreeAndFiveAreFizzBuzz() {
        for (int i = 1; i &amp;lt;= 100; i++) {
            if ((i % 3 == 0) &amp;amp;&amp;amp; (i % 5 == 0)) {
                assertEquals(&quot;FizzBuzz&quot;, unit.apply(i));
            }
        }
    } 
// ...and so on
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;or this, which he said &lt;em&gt;“feels wildly unsatisfactory … It’s hard to see this as really rigorously testing anything.”&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;    @Test
    public void testSomeJudiciouslyChosenValues() {
        assertEquals(&quot;Fizz&quot;, unit.apply(3));
        assertEquals(&quot;4&quot;, unit.apply(4));
        assertEquals(&quot;Buzz&quot;, unit.apply(5));
        assertEquals(&quot;FizzBuzz&quot;, unit.apply(15));
        // just in case
        assertEquals(&quot;FizzBuzz&quot;, unit.apply(30));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Are any of these tests good enough? Which ones provide best coverage and communication? I’ll leave you to mull that over while I &lt;a href=&quot;https://www.strava.com/activities/831826153&quot;&gt;ride my bike&lt;/a&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;OK, I’m back. What was your verdict? Would you be happy with any of those tests for FizzBuzz?&lt;/p&gt;

&lt;p&gt;For me, we can discount &lt;code&gt;testSomeJudiciouslyChosenValues&lt;/code&gt; easily, but only because it doesn’t go out of its way to describe the system under test. Using judiciously chosen values to demonstrate and verify the behaviour of a system isn’t of itself a bad thing. If it was, pulling on this thread would unravel pretty much all of Behaviour Driven Design.&lt;/p&gt;

&lt;p&gt;Looking at the set beginning with &lt;code&gt;multiplesOfThreeButNotFiveAreFizz&lt;/code&gt;, I agree with Dominic - they are pretty obscure and intractable. But then, they were probably designed to show theories in a good light, so perhaps they are a straw man. The fact is that testing the first 100 numbers is arbitrary and misses the opportunity to communicate the fact that FizzBuzz has period of 15. A sane implementation can be verified in far fewer examples, and an insane implementation, one that looks at the test and goes out of it’s way to break it, could throw &lt;code&gt;UnsupportedOperationException&lt;/code&gt; at 101, or return “Banana” at random with a probability of 1:10000.&lt;/p&gt;

&lt;p&gt;The traditional goal of unit tests is to prevent accidental breakage during modifications of this or other code - regression. Well-written tests can also serve to demonstrate what the code does - communication. In TDD they have another job, to guide the implementation. I would argue that the tests we wrote actually TDDing FizzBuzz here fulfil the three roles of regression, communication and guiding the implementation pretty well. They helped us write the code, the names tell us what the code does, and the examples exemplify the names.&lt;/p&gt;

&lt;p&gt;There have been times when the tests that I have written to guide the implementation of a system have not communicated well, or have holes that might allow regressions to slip through (what is &lt;code&gt;fizzBuzz(0)&lt;/code&gt;?). Before we consider the job done, we should look at the tests that helped us drive the design and judge them against the regression and communication criteria. If they fall short, then add examples, refactor the tests, maybe even recast them as theories. Don’t expect the test artifact of TDD to be perfect first time, because &lt;a href=&quot;http://www.drdobbs.com/tdd-is-about-design-not-testing/229218691&quot;&gt;TDD Is About Design, Not Testing&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Tune in later for &lt;a href=&quot;/tdd-v-testing-part2.html&quot;&gt;Part 2&lt;/a&gt;, where I’ll repeat TDD FizzBuzz using JUnit theories from the outset.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>More Kotlin Extension Fun</title>
   <link href="http://0.0.0.0:4000/more-kotlin-extension-fun.html"/>
   <updated>2016-10-06T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/more-kotlin-extension-fun</id>
   <content type="html">&lt;p&gt;This is a follow-up to my last post, &lt;a href=&quot;/extension-functions-can-be-utility-functions.html&quot;&gt;Extension Functions Can Be Utility Functions&lt;/a&gt;. Here I’ll look at more pros and cons of extension functions.&lt;/p&gt;

&lt;p&gt;The article brought out 3 extension function use-cases.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Adding a little local expressiveness with private methods like &lt;code&gt;JsonNode.toAddress()&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Adding methods you wish were available on types that you don’t own - &lt;code&gt;JsonNode.getNonBlankText(name: String)&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Keeping your own classes small by defining operations as extension functions rather than actual methods - &lt;code&gt;AccessType.toUIString()&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;On the Kotlin Slack Channel, Daniel Wellman asked&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“How do you decide when methods should be extension functions and when they should be members (functions) on classes/objects _that you own_?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Nathan Armstrong replied&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“I think it’s usually when it encapsulates operations on a type in some context tangential to the one the type was made for.  For example, when writing code that intersects two domains or concerns, using extension methods can help you use your existing types more naturally alongside one another without leaking that local utility into other parts of the codebase”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;He’s right. So right that I’m going to say that again with many more words and claim the credit.&lt;/p&gt;

&lt;p&gt;Most of my Java projects have ended up with a package of domain objects - &lt;code&gt;Person&lt;/code&gt;, &lt;code&gt;Address&lt;/code&gt; etc. Kotlin makes these nice and simple with data classes, and when 1.1 allows inheritance these will become even more useful.&lt;/p&gt;

&lt;p&gt;Over time these classes accrete operations that make sense to our application. Things like &lt;code&gt;Person.asJson()&lt;/code&gt; and &lt;code&gt;Address.isCloseMyHouse()&lt;/code&gt;. These operations dilute the essence of the class for our happy convenience, but after a while we can’t see the platonic wood for expedient trees.&lt;/p&gt;

&lt;p&gt;Extension functions let us express the PersonNess in the &lt;code&gt;Person&lt;/code&gt; class, and the JSONness elsewhere. In this case maybe type-classes would be better, but for now, we can move our JSON writing and useful-to-us-but-not-really-essential operations off of the class and into extension functions.&lt;/p&gt;

&lt;p&gt;A nice side-effect of this is that we can build our domain classes in a module that doesn’t have dependencies on Jackson and some SQL library and the whole of the rest of our app. Maybe we’ll finally get reuseable abstractions for those fundamental real-world things that every app has to implement from scratch because of all the special cases that define our Customer rather than yours.&lt;/p&gt;

&lt;p&gt;A word of warning though. Extension functions are not polymorphic. If I have&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Person

class Customer: Person

fun Person.toJson() = ...

fun Customer.toJson() = ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;the bindings are as follows:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;Person().toJson() // calls Person.toJson()

Customer().toJson() // calls Customer.toJson()

val person: Person = readCustomer(42)
person.toJson() // calls Person.toJson() no matter what the actual type of person
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you like this, &lt;a href=&quot;www.natpryce.com&quot;&gt;Nat Pryce&lt;/a&gt; and I are going to be talking about Expressive Kotlin at the &lt;a href=&quot;https://info.jetbrains.com/Kotlin-Night-London.html&quot;&gt;Kotlin Night London&lt;/a&gt; next Wednesday, 12 October 2016.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href=&quot;http://www.springernature.com&quot;&gt;Springer Nature&lt;/a&gt; for allowing me to publish examples from their code. If you’re looking for a Kotlin job in London, they are hiring - please contact me using one of the links in the sidebar.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Extension Functions Can Be Utility Functions</title>
   <link href="http://0.0.0.0:4000/extension-functions-can-be-utility-functions.html"/>
   <updated>2016-10-05T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/extension-functions-can-be-utility-functions</id>
   <content type="html">&lt;p&gt;I enjoyed &lt;a href=&quot;https://medium.com/@dimsuz/extension-functions-are-not-utility-functions-74a5f9b53892#.o57pbn5k2&quot;&gt;Extension functions are not utility functions&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I thought that I disagreed, but on more careful reading maybe not. Instead I’ll pull out some extension functions from my current codebase.&lt;/p&gt;

&lt;p&gt;We’re finding that extension functions are a simple way to make code more expressive.&lt;/p&gt;

&lt;p&gt;Without an extension function:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private fun addressFrom(node: JsonNode): Address = ...

val addresses = nodes.map { addressFrom(it) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With an extension function:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private fun JsonNode.toAddress(): Address = ...

val addresses = nodes.map { it.toAddress() }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You might the find first example more readable like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private fun toAddress(node: JsonNode): Address = ...

val addresses = nodes.map(::toAddress)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;in which case fill yer boots, but my mind doesn’t work that way.&lt;/p&gt;

&lt;p&gt;Extension functions work well here, but the place where they really shine is method chaining.&lt;/p&gt;

&lt;p&gt;Without them:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private fun addressFrom(node: JsonNode): Address = ...

private fun isInUK(address: Address): Boolean = ...

val isInUK = isInUK(addressFrom(node))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Extension functions don’t make you turn your brain inside out:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;private fun JsonNode.toAddress(): Address = ...

private fun Address.isInUK(): Boolean = ...

val isInUK = node.toAddress().isInUK()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You may have noticed the &lt;code&gt;private&lt;/code&gt; in the examples above - most of the extension functions that we write this way are used  locally - just to make a few lines of code more intuitive. But that’s by no means universally true - this is from some library code to extend Jackson in more general ways:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun JsonNode.getExpected(name: String): JsonNode = get(name) ?: throw MissingPropertyException(&quot;property '$name' is missing&quot;)

fun JsonNode.getNonBlankText(name: String) = getExpected(name).asText().apply {
    if (isBlank()) throw JsonInterpretationException(&quot;property $name is blank&quot;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I had wondered whether this style was best suited to operations on types that we don’t own. But I find we have code that acts on our own types:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun suggestionsTemplateDataFor(suggestions: List&amp;lt;JournalJson&amp;gt;) = mapOf(
    &quot;results&quot; to suggestions.withOAText()
)

private fun List&amp;lt;JournalJson&amp;gt;.withOAText(): List&amp;lt;Map&amp;lt;String, Any?&amp;gt;&amp;gt; = this.map { it.withOAText() }

private fun JournalJson.withOAText() = TreeMap(this.asPropertyMap().plus( &quot;openAccessText&quot; to this.accessType.toUIString()))

private fun AccessType.toUIString() = when (this) {
    AccessType.OPEN_ACCESS -&amp;gt; &quot;Yes&quot;
    AccessType.SUBSCRIPTION -&amp;gt; &quot;No&quot;
    AccessType.OPEN_CHOICE -&amp;gt; &quot;Optional&quot;
    else -&amp;gt; &quot;Unknown&quot;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here &lt;code&gt;JournalJson&lt;/code&gt; and &lt;code&gt;AccessType&lt;/code&gt; are simple data classes, unencumbered by all the operations that the rest of the system would like them to have; because they can define operations like &lt;code&gt;withOAText()&lt;/code&gt; as extension functions when they need them. And if defining an extension on &lt;code&gt;List&amp;lt;JournalJson&amp;gt;&lt;/code&gt; isn’t a utility function I don’t know what is, but here it really helps us to at least get the gist of what is going on at the top level.&lt;/p&gt;

&lt;p&gt;Hidden in there is a call to&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun Any.asPropertyMap(): Map&amp;lt;String, Any?&amp;gt; = SpaceBlanket(this)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which &lt;em&gt;is&lt;/em&gt; the archetypal extension function definition - high-level and fundamental.&lt;/p&gt;

&lt;p&gt;There are more thoughts on this subject in a follow up article - &lt;a href=&quot;/more-kotlin-extension-fun.html&quot;&gt;More Kotlin Extension Fun&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you like this, &lt;a href=&quot;www.natpryce.com&quot;&gt;Nat Pryce&lt;/a&gt; and I are going to be talking about Expressive Kotlin at the &lt;a href=&quot;https://info.jetbrains.com/Kotlin-Night-London.html&quot;&gt;Kotlin Night London&lt;/a&gt; next Wednesday, 12 October 2016.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href=&quot;http://www.springernature.com&quot;&gt;Springer Nature&lt;/a&gt; for allowing me to publish examples from their code. If you’re looking for a Kotlin job in London, they are hiring - please contact me using one of the links in the sidebar.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>On Epics</title>
   <link href="http://0.0.0.0:4000/on-epics.html"/>
   <updated>2016-07-28T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/on-epics</id>
   <content type="html">&lt;p&gt;The phrase epic has connotations. Epics are embarked on until they are completed. They require heroics. People don’t suspend one epic in order to start another. An epic is only successful at its end.&lt;/p&gt;

&lt;p&gt;Our agile planning should be more fluid and less valiant. We should be prepared to change course. We should pick our battles carefully. At every stage we should pick the story that delivers the best return on investment. We should seek to deliver value every day, not just at the end of a piece of work.&lt;/p&gt;

&lt;p&gt;By all means break a story into tasks. Please do categorise stories by theme if it helps. But be wary of embarking on an epic.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>On Minimal</title>
   <link href="http://0.0.0.0:4000/on-minimal.html"/>
   <updated>2016-06-13T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/on-minimal</id>
   <content type="html">&lt;p&gt;Despite not having seen him for perhaps 20 years, I continue to learn from &lt;a href=&quot;https://www.youtube.com/user/paulearwicker&quot;&gt;Paul Earwicker&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;One thing that still resonates with me was his advice on design. Say you were tasked with producing the lightest possible bike frame that wouldn’t fail under normal use, but had no access to modelling tools. How should you proceed?&lt;/p&gt;

&lt;p&gt;You could design a frame that was obviously strong enough, but how then would you know how much material you could remove to make it light enough? And where would you remove it from? No, faced with this challenge the rational approach (provided you don’t value your front teeth) is to make a frame that is not strong enough, and ride it. When it breaks, reinforce the places where it broke. Repeat until it doesn’t break, and you will have a minimal frame.&lt;/p&gt;

&lt;p&gt;When it comes to software, I’m working to deliver a Minimal Viable Product. But my customers and I are constantly disagreeing on whether a feature or enhancement is in or out of the minimal set. They want to add things, I want to deliver what we have. Why? Because as with the bike frame, it’s easy to know minimal when you see it, but hard to predict what makes a thing viable. If you actually want to ship an MVP, you have to approach it from below, delivering a product that turns out not to be viable and adding to it until it is. You have to look back and say, ah, that minimal release was the first one that was viable.&lt;/p&gt;

&lt;p&gt;Why are my customers fighting this? Well they’re rational too, and know that a consequence of this process is that your first few releases will be failures. If you can’t survive the embarrassment of walking home with a broken bike frame, then maybe it’s best to make sure that your MVP process is a bit less public.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>How I Learned to Write Legacy Code</title>
   <link href="http://0.0.0.0:4000/imperial-2016.html"/>
   <updated>2016-05-23T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/imperial-2016</id>
   <content type="html">&lt;p&gt;The following is the text of a talk I gave at Imperial College in February. The images are those used in the talk, and are used here without explicit permission.&lt;/p&gt;

&lt;p&gt;Hello. As Antonio says I’m Duncan McGregor. I graduated with a Physics degree from Imperial in 1989, when Windows looked like this.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/en/8/8f/Windows_2.1.png&quot; alt=&quot;Windows 2.1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;From Imperial I joined the Ministry of Defence Management Training Fast Stream, where I worked in various mainly R&amp;amp;D roles. I left the MoD in 1994, when Windows looked like this.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/en/7/73/Windows_3.11_workspace.png&quot; alt=&quot;Windows 3.11&quot; /&gt;&lt;/p&gt;

&lt;p&gt;and had a few permanent jobs in software companies before taking the plunge and becoming a contractor in 2000, when Windows looked like this.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://q2.rlogin.dk/sites/windows-2000-advanced-server/1.png&quot; alt=&quot;Windows 2000&quot; /&gt;.&lt;/p&gt;

&lt;p&gt;These days (when I don’t even know what Windows looks like any more) I work mainly in London, largely on the JVM, and in various different application areas, most recently in academic publishing.&lt;/p&gt;

&lt;p&gt;When Robert asked me to talk about legacy code and participate in your discussion, I thought I’d dredge up a few war stories and see if we, or at least I, can learn something from my career.&lt;/p&gt;

&lt;p&gt;My first real exposure to commercial code was at MTA, a small consultancy I joined after I was ejected from the MoD. The consultancy had just been commissioned to extend a Lisp expert system that planned Royal Marines amphibious landings – essentially which troops and equipment should leave which ships on which boats and helicopters at what time to hit the beach at H-hour, with the most scary marines at the front.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;http://www.royalnavy.mod.uk/~/media/royal%20navy%20responsive/images/news/royal%20marines/general%20royal%20marine%20photos/140527%20last%20phase%201664/fx140126002.jpg?mh=447&amp;amp;mw=980&amp;amp;thn=0&quot; alt=&quot;Royal Marines Landing Craft&quot; /&gt;&lt;/p&gt;

&lt;p&gt;I bring this project up because (with a bit of a bash) it fits the original definition of legacy – essentially “something of value left by old people to young people.” This wasn’t an albatross - it was an asset. Just because I hadn’t written it didn’t mean that it was bad - it did the job, was capable of being extended, and made the company more money.&lt;/p&gt;

&lt;p&gt;This contrasts with my next job, at ESL, a company that wrote X.400 email systems. No one remembers X.400 any more – it was email designed by international standards bodies rather than Unix hackers, and so died the death that most over-engineered solutions do when disintermediated by free software. The codebase, and the people who knew how to tend it, were the company’s only asset – and when I joined they had just been bought out by an American firm who had won a contract with the US Department of Defence and needed code to fulfil it.&lt;/p&gt;

&lt;p&gt;Unfortunately this codebase was much more like our usual software definition of legacy – old and hard to work with. It was, I think, originally quite well engineered – there were sensible conventions, and reasonable encapsulation for a C codebase. But this was lost under the accretion of years of new features and misunderstandings. I remember that, years after leaving the job, I finally realised that the memory management scheme – where heaps were allocated by upstream code to allow downstream functions to return pointers – was a clever way of taking advantage of the pipeline nature of message decoding to make up for lack of garbage collection. But if anyone at the company understood that by the time I arrived, they certainly didn’t explain it. Instead we had heuristics for when heaps had to be allocated and destroyed that seemed arbitrary because the original model had been forgotten.&lt;/p&gt;

&lt;p&gt;The result of this and other code issues was painfully slow progress and eventual bankruptcy, so I took a job at Roke Manor Research, then a part of Siemens. Work there was on nice new R&amp;amp;D projects with rubbish logos,&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/assets/WacX LOGO.bmp&quot; alt=&quot;WacX&quot; /&gt;&lt;/p&gt;

&lt;p&gt;so I learned little about legacy code - until I discovered Extreme Programming.&lt;/p&gt;

&lt;p&gt;This was 1999, and it’s easy to forget just how revolutionary Ward Cunningham and Kent Beck‘s ideas were. Up to this point we considered that finding all the requirements for a software system before starting work was a worthy goal. That way the system could be designed to meet those requirements – and the team could implement the design with least waste.&lt;/p&gt;

&lt;p&gt;At least, that’s true for the first version, but after that, you have the system as it is and have to work out how to hack Version 2’s features into the existing system. I can’t find the quote, but Kent said something like – “I read that 80% of all effort on software is maintenance – and wondered how we could get that up to 95%.”&lt;/p&gt;

&lt;p&gt;I won’t claim that I really understood this at the time, but it is crucial. Your first release is not only building the software – it’s building the team that builds the software. If when it delivers Version 1, that team has only learnt how to implement features given a clean slate, things are going to go very wrong when faced with a list of features and an existing codebase.&lt;/p&gt;

&lt;p&gt;This was a lesson that was evidently not learned by Sony - my first client when I started contracting. It gave the prototype Set Top Box application my team had developed to another team to ‘productionise.’  But it was a validation of XP when it comes to code quality. The team took the code and, having studied it, came back and asked, “How did you guys develop this – because we want to be doing that!” That’s an existence proof for a way of writing legacy code that people want to work in – Test Driven Development and You Ain’t Gonna Need It.&lt;/p&gt;

&lt;p&gt;Around this time I took a commission to write an interface between the Tradacoms EDI system and a soft-furnishing manufacturer’s accounting package. I didn’t know it at the time, but over 10 years this system would process hundreds of millions of pounds worth of orders and invoices. (If I had have known, I would have charged considerably more.) I wrote the software in Python, because I wanted to learn the language. This is not the best reason for choosing a technology for a system that you’re going to end up supporting for over a decade.&lt;/p&gt;

&lt;p&gt;The software was upgraded perhaps 8 times over its lifetime. Every time I returned to the code it was after enough of a break to have to work out how it functioned just from the code and documentation – it was legacy code every time. Python isn’t ideal for this – the dynamic typing makes reasoning with the code harder than in a statically typed language. Nevertheless, in the dozen years that it was running data was never data lost because of a coding error, in fact I don’t think I ever had a bug report that wasn’t actually a feature request. How? Well I knew that this was critical code and wrote tests accordingly, both at the unit and acceptance level, and more regression tests to make sure that upgraded code gave the same output as its predecessor on old messages.&lt;/p&gt;

&lt;p&gt;Returning to a piece of code after a break is also an ideal time to add the comments and tests that would have helped you understand the code quicker this time had they been there. I really do think that this codebase got better with age – it came to express the problem domain so that new features were often just a matter of configuration or wiring up existing code in a new way. This is of course legacy code nirvana – and I’ve not been lucky enough to work on another system that aged so well.&lt;/p&gt;

&lt;p&gt;That may be because it’s so much easier to work on your own code – even when the old you wasn’t half as good as the current you is. In late 2002 I started another XP project in Sony – a little video editing product that a pair of us released in 9 months and went on to extend. I then left the project – at that point the code wasn’t perfect, but it was really fit for purpose, with a good architecture and test coverage.&lt;/p&gt;

&lt;p&gt;I would return to work on the same codebase, now being extended by a team of 6 plus QA, a little over 2 years later. Actually it was in remarkably good shape – with much of the original architecture intact, proving that an evolutionary design can support change. Crucial was that my original partner on the project was still in charge, so that our discovery of solutions and ways of thinking about the domain had not been lost. He also kept the culture of tests, if not always TDD, so that new code was forced by this constraint into being at least more than usually habitable.&lt;/p&gt;

&lt;p&gt;This theme of tests driving code quality resurfaced in 2012 when I went to work on a major satellite broadcaster’s set top box software. When I arrived this had recently had its first release, albeit 4 years late. Some of that time had been spent retrofitting tests to the codebase.&lt;/p&gt;

&lt;p&gt;Now I suppose if you agree with Michael Feathers - that legacy code is code without tests - it should logically follow that you can turn your decaying stately home into a plush modern mansion just by adding the tests that weren’t there.&lt;/p&gt;

&lt;p&gt;It won’t surprise you to know that this is not true. Test Driven Development works because it makes writing software with sensible seams, logical interfaces and defined dependencies the path of least resistance. But if you’re tasked with adding tests to existing code - it’s probably easier not to refactor - just throw mocks at the problem, and if they aren’t powerful enough, then surely powermocks will be. The resulting tests will then prevent you from changing the behaviour of your code accidentally, or, unfortunately, deliberately.&lt;/p&gt;

&lt;p&gt;Moving onto another contract at a major fashion retailer reinforced the lesson that tests done badly can prevent any change. Here things were better factored but hobbled by a test suite that tied the tests to the Spring dependency injection framework. The result was individual tests that could take seconds to start, tests that required chasing through the filesystem and class hierarchy to find the data that they relied on, and tests that depended on other tests having run first. And don’t get me started on the tests that started failing on 1 Jan 2015 – my second week, because that was as far into the future as far as anyone could imagine this codebase lasting.&lt;/p&gt;

&lt;p&gt;What went wrong here? I suppose that in the end there were just too many people working on the code for too long, in a culture of ‘good enough.’ But the truth is that most developers are not good enough to prevent poorly architected systems from eventually collapsing under their own weight, most architects are not good enough to design systems that can cope with average developers, and most clients won’t pay for the overhead in any case.&lt;/p&gt;

&lt;p&gt;But I don’t want to end on a negative note! I’ve just come from a meeting planning work on a multi-man-decade academic peer-review system for a client that does understand the importance of these things (and will be hiring in the summer!) In the end, what we do is engineering – it requires knowledge, experience, creativity and taste – and these are the very things that can keep our legacy code a habitable place to work.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Konsent</title>
   <link href="http://0.0.0.0:4000/konsent.html"/>
   <updated>2016-05-12T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/konsent</id>
   <content type="html">&lt;p&gt;I’ve just released &lt;a href=&quot;https://github.com/dmcg/konsent&quot;&gt;Konsent&lt;/a&gt;, an acceptance testing library for Kotlin.&lt;/p&gt;

&lt;p&gt;The basic idea is that you can write your tests in a nice IDE-friendly and refactorable Kotlin DSL, but they generate
Gherkin that your customer can read and approve as the spec.&lt;/p&gt;

&lt;p&gt;So you write this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@RunWith(Konsent::class)
@Preamble(
    &quot;As a developer named Duncan&quot;,
    &quot;I want to know that example.com is up and running&quot;)
class KonsentExampleTests : ChromeAcceptanceTest() {

    val duncan = actorNamed(&quot;Duncan&quot;)

    @Scenario(1) fun `Example_dot_com loads`() {
        Given(duncan).loadsThePageAt(&quot;http://example.com&quot;)
        Then(duncan) {
            shouldSee(::`the page location`, pathContains(&quot;example.com&quot;))
            shouldSee(::`the page title`, equalTo(&quot;Example Domain&quot;))
            shouldSee(::`the page content`, containsALink(&quot;More information...&quot;, &quot;http://www.iana.org/domains/example&quot;))
        }
    }

    @Scenario(2, &quot;Following a link from example.com&quot;) fun cant_have_dots_in_quoted_method_names() {
        Given(duncan).loadsThePageAt(&quot;http://example.com&quot;)
        When(duncan).followsTheLink(&quot;More information...&quot;, &quot;http://www.iana.org/domains/example&quot;)
        Then(duncan).shouldSee(::`the page location`, equalTo(URI(&quot;http://www.iana.org/domains/reserved&quot;)))
    }

    @Scenario(3) fun `Dispensing with the given when then`() {
        duncan.he.loadsThePageAt(&quot;http://example.com&quot;)
        duncan.he.followsTheLink(&quot;More information...&quot;, &quot;http://www.iana.org/domains/example&quot;)
        duncan.shouldSee(::`the page location`, equalTo(URI(&quot;http://www.iana.org/domains/reserved&quot;)))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and they read this&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-gherkin&quot;&gt;Feature: Konsent Example Tests
    As a developer named Duncan
    I want to know that example.com is up and running

    Scenario: Example_dot_com loads
        Given Duncan loads the page at &quot;http://example.com&quot;
        Then Duncan sees the page location &quot;location contains &quot;example.com&quot;
        and Duncan sees the page title is equal to &quot;Example Domain&quot;
        and Duncan sees the page content contains a link [More information...](http://www.iana.org/domains/example)

    Scenario: Following a link from example.com
        Given Duncan loads the page at &quot;http://example.com&quot;
        When Duncan follows the link [More information...](http://www.iana.org/domains/example)
        Then Duncan sees the page location is equal to http://www.iana.org/domains/reserved

    Scenario: Dispensing with the given when then
        Duncan loads the page at &quot;http://example.com&quot;
        Duncan follows the link [More information...](http://www.iana.org/domains/example)
        Duncan sees the page location is equal to http://www.iana.org/domains/reserved
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thanks to my patrons at &lt;a href=&quot;http://springernature.com&quot;&gt;Springer Nature&lt;/a&gt;, on whose dime this approach has been developed. We’re
hiring, so &lt;a href=&quot;https://twitter.com/duncanmcg&quot;&gt;get in touch&lt;/a&gt; if you’re in London and this stuff interests you.&lt;/p&gt;

&lt;p&gt;Stay tuned - I’m planning a post soon on how to implement a DSL like this in Kotlin.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Interface v Implementation</title>
   <link href="http://0.0.0.0:4000/interface-v-implementation.html"/>
   <updated>2016-05-11T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/interface-v-implementation</id>
   <content type="html">&lt;h1 id=&quot;context&quot;&gt;Context&lt;/h1&gt;

&lt;p&gt;Here at Springer Nature &lt;a href=&quot;https://www.linkedin.com/jobs/springer-science-business-media-jobs&quot;&gt;(still hiring :-)&lt;/a&gt; we have a single-page webapp that recommends academic journals via a small web service which in turn queries an Elastic Search index. The Elastic Search index needs to be refreshed periodically - we’re not sure how often, probably once a month or so. The data that is indexed comes from an XML web service, merged and transmogrified in XPath’y ways.&lt;/p&gt;

&lt;p&gt;If you’ve been reading along, yes, this is the same refresher I looked at in the first &lt;a href=&quot;/mocks-v-approvals-tests-part1.html&quot;&gt;2 episodes&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;now-to-run-it&quot;&gt;Now to Run It&lt;/h1&gt;

&lt;p&gt;We’d finished the code to update the index, and just needed a way to run it periodically. My colleague imported Quartz, and created a dummy Job implementation that printed “Hello World” on the 28th day of every month, courtesy of Quartz’s &lt;code&gt;CronTrigger&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;IndexUpdater&lt;/code&gt; class has a constructor that takes the source and destination details, and it has a run() method that we’d like Quartz to call on the configured schedule - simples.&lt;/p&gt;

&lt;p&gt;I started to tackle this task on the train on the way into work. The Internet connection was patchy, masking the fact that the Quartz website was down. But I had the source, and it seemed to be saying that I had to create a &lt;code&gt;JobDetail&lt;/code&gt; object (via the inevitable &lt;code&gt;JobDetailBuilder&lt;/code&gt;). The &lt;code&gt;JobDetail&lt;/code&gt; references an implementation of a &lt;code&gt;Job&lt;/code&gt; interface, that has an execute method. So all I have to do is make my &lt;code&gt;IndexUpdater&lt;/code&gt; implement &lt;code&gt;Job&lt;/code&gt;, and rename run to execute!&lt;/p&gt;

&lt;p&gt;Except that isn’t what Quartz does. It doesn’t take an instance of a class that implements &lt;code&gt;Job&lt;/code&gt;. It takes a reference to a class that implements &lt;code&gt;Job&lt;/code&gt;, instantiates it using a no-arg constructor, then calls &lt;code&gt;newlyCreatedInstanceOfJob.execute()&lt;/code&gt;. It requires reflection to do this, its one, erm, job.&lt;/p&gt;

&lt;p&gt;How on earth did this get to be the case? How is the simple case of just calling a method on an object not the default? Somewhat tongue-in-cheek I tweeted:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://twitter.com/duncanmcg/status/712918584658419712&quot;&gt;“Is there any way to persuade Quartz to - how to describe this crazy use case - invoke a function on a schedule?”&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and then asked the &lt;a href=&quot;http://stackoverflow.com/q/36196191/97777&quot;&gt;same question on Stack Overflow&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Of course you can write code to thunk between the simple case and the reflecto-magic case …, but surely it should be that the reflecto-magic is implemented in terms of the simple method call, not vice versa? Quartz developers, how did it get like that?&lt;/p&gt;

&lt;h1 id=&quot;what-quartz-really&quot;&gt;What Quartz, Really?&lt;/h1&gt;

&lt;p&gt;Arriving at work, I was asked, “Why are you using Quartz if its interface is so bad?”&lt;/p&gt;

&lt;p&gt;Now while there is a bit of me that distrusts the work of programmers who would have made the &lt;code&gt;JobDetail&lt;/code&gt; their first choice, I do think that parsing Cron expresssions, running a job on schedule, making sure that a job can only be running one instance, recovering from errors etc, is a complex task. I’m pretty sure that if I tried it there would be at least one bug remaining after a day or two or work. I first used Quartz at least 10 years ago and there are thousands of projects depending on it - the chances are it’s reliable and stable where it counts, even if enterprisey and naff in its interface.&lt;/p&gt;

&lt;p&gt;Even after banging my head against that interface, we had scheduled tasks running with a configurable Cron pattern and invokable on demand via a POST in under 2 hours of work. Standing on the shoulders of giants should be our default choice, even if we sometimes have to wear orthotics to be comfortable there.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>JMock and Kotlin</title>
   <link href="http://0.0.0.0:4000/jmock-and-kotlin.html"/>
   <updated>2016-05-01T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/jmock-and-kotlin</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://www.jmock.org/&quot;&gt;JMock&lt;/a&gt; may have lost the mocking war, but for the London crowd it’s still the go-to mocking tool.
It turns out that a little Kotlin fairy-dust can make it even more expressive.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;/mocks-v-approvals-tests-part2.html&quot;&gt;my last post&lt;/a&gt; we saw a pretty vanilla use of JMock. In fact there was &lt;em&gt;one&lt;/em&gt; nice
Kotlin’ism, defining an extension method on Mockery. So where in Java we would write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;mockery.checking(new Expectations() { {
    oneOf(progress).reset(2);
    oneOf(indexer).createIndex();
} })
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;in Kotlin, by defining&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun Mockery.expecting(block: MyExpectations.() -&amp;gt; Unit) {
   this.checking(MyExpectations().apply(block))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;we can write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;mockery.expecting {
    oneOf(progress).reset(2)
    oneOf(indexer).createIndex()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In addition, in the name of more readable tests, I had added a subclass of Expectations
to allow me to write, for example&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;mockery.expecting {
   givenActiveJournalIds(
       &quot;1&quot; to throwException(RuntimeException(&quot;oops&quot;)),
       &quot;2&quot; to returnValue(journal2))
   }
   ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was achieved with&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class MyExpectations : Expectations() {
   fun givenActiveJournalIds(vararg idResultPairs: Pair&amp;lt;String, Action&amp;gt;) {
       allowing(journals).loadActiveIds()
       will(returnValue(idResultPairs.map { it.first }))
       idResultPairs.forEach { pair -&amp;gt;
           allowing(journals).loadJournalWithArticles(pair.first, 99)
           will(pair.second)
       }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;which is tighter in Kotlin, but nothing that you couldn’t do in Java.&lt;/p&gt;

&lt;p&gt;Looking at a one of the tests, this plugs together into something like&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Test fun reports_exceptions_and_continues() {
   mockery.expecting {
       val x = RuntimeException(&quot;oops&quot;)

       givenActiveJournalIds(
           &quot;1&quot; to throwException(x),
           &quot;2&quot; to returnValue(journal2))

       oneOf(progress).reset(2)
       oneOf(indexer).createIndex()

       never(indexer).index(JournalJson(journal1))
       oneOf(progress).exception(&quot;1&quot;, x)

       oneOf(indexer).index(JournalJson(journal2))
       oneOf(progress).indexed(journal2)
   }
   refresher.refresh(journals, indexer, emptySet())
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This isn’t bad, but one of JMock’s problems is that it doesn’t differentiate between interactions
that are queries, and those that are operations. In this case the refresher queries the &lt;code&gt;journals&lt;/code&gt;
to find what needs to be indexed, then operates on the &lt;code&gt;indexer&lt;/code&gt; to add them. Introducing
&lt;code&gt;givenActiveJournalIds&lt;/code&gt; gives a clue, but it would be nice to see the split more formally.&lt;/p&gt;

&lt;p&gt;What I’d like to see is&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Test fun reports_exceptions_and_continues() {
    val x = RuntimeException(&quot;oops&quot;)
    mockery.given {
        activeJournalIds(
            &quot;1&quot; to throwException(x),
            &quot;2&quot; to returnValue(journal2))
    }.whenRunning {
        refresher.refresh(journals, indexer, emptySet())
    }.thenExpect {
        oneOf(progress).reset(2)
        oneOf(indexer).createIndex()

        never(indexer).index(JournalJson(journal1))
        oneOf(progress).exception(&quot;1&quot;, x)

        oneOf(indexer).index(JournalJson(journal2))
        oneOf(progress).indexed(journal2)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This can be achieved through 2 extension methods and a little class -&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun Mockery.expecting(expectations: Expektations.() -&amp;gt; Unit): Mockery {
    this.checking(Expektations().apply(expectations))
    return this
}

fun Mockery.whenRunning(block: () -&amp;gt; Unit) = ThenClause(this, block)

class ThenClause(private val mockery: Mockery, private val block: () -&amp;gt; Unit) {
    fun thenExpect(expectations: Expektations.() -&amp;gt; Unit) {
        mockery.expecting(expectations)
        block()
        mockery.assertIsSatisfied()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Actually that trick &lt;a href=&quot;https://github.com/dmcg/nowthen&quot;&gt;can be played in Java 8 too&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you’re really eagle-eyed, you may have noticed &lt;code&gt;Expektations&lt;/code&gt; pop up in that example.
That’s to support my final trick, an extension method on &lt;code&gt;Nothing&lt;/code&gt;. Why?&lt;/p&gt;

&lt;p&gt;Well what if we wanted to simulate an exception in the indexing?&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Test fun `reports exceptions in indexing and continues`() {
    val x = RuntimeException(&quot;oops&quot;)
    mockery.given {
        activeJournalIds(
            &quot;1&quot; to returnValue(journal1),
            &quot;2&quot; to returnValue(journal2))
    }.whenRunning {
        refresher.refresh(journals, indexer, emptySet())
        executor.runUntilIdle()
    }.thenExpect {
        oneOf(progress).reset(2)
        oneOf(indexer).createIndex()

        oneOf(indexer).index(JournalJson(journal1))
        will(throwException(x))
        oneOf(progress).exception(&quot;1&quot;, x)

        oneOf(indexer).index(JournalJson(journal2))
        oneOf(progress).indexed(journal2)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That &lt;code&gt;will()&lt;/code&gt; as a separate statement has always bothered me about JMock - it should
bind to the previous statement, but can’t because &lt;code&gt;indexer.index(...)&lt;/code&gt; returns &lt;code&gt;Unit&lt;/code&gt;
(&lt;code&gt;void&lt;/code&gt; in Java). In Kotlin we can define&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Expektations: Expectations() {
    fun Any?.will(action: Action) = super.will(action)
    // fun Nothing.will(action: Action) = super.will(action) Update 2016-05-17 - looks like this isn't needed, as Unit extends Any
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and now within our expectation blocks we can write&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-koklin&quot;&gt;{
    oneOf(indexer).index(JournalJson(journal1)).will(throwException(x))
    // or
    allowing(journals).loadJournalWithArticles(&quot;1&quot;, 99).will(returnValue(journal1))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With a bit of work I think that would allow a typed JMock &lt;code&gt;Action&lt;/code&gt; so that you could only
&lt;code&gt;returnValue&lt;/code&gt; with the correct type, but I haven’t pulled on that thread yet.&lt;/p&gt;

&lt;p&gt;The final bonus marks in this post go for spotting&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Test fun `reports exceptions in indexing and continues`()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ignoring the fact that it breaks &lt;a href=&quot;http://prismjs.com/&quot;&gt;Prism&lt;/a&gt;’s Kotlin highlighter, this hack was pointed out by
&lt;a href=&quot;http://natpryce.com&quot;&gt;Nat Pryce&lt;/a&gt; - backticks allow spaces in method names, giving beautifully
readable specs in code and test runners.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Mocks v Approvals Tests Part 2</title>
   <link href="http://0.0.0.0:4000/mocks-v-approvals-tests-part2.html"/>
   <updated>2016-04-23T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/mocks-v-approvals-tests-part2</id>
   <content type="html">&lt;p&gt;Aka: Test Driven Design v Test Driven Development&lt;/p&gt;

&lt;h1 id=&quot;context&quot;&gt;Context&lt;/h1&gt;

&lt;p&gt;In &lt;a href=&quot;/mocks-v-approvals-tests-part1.html&quot;&gt;Part 1&lt;/a&gt; we looked at testing an algorithm using Approvals Tests.&lt;/p&gt;

&lt;p&gt;In this Part 2, we’ll start again using JMock, and see what happens.&lt;/p&gt;

&lt;h2 id=&quot;quick-recap&quot;&gt;Quick Recap&lt;/h2&gt;

&lt;p&gt;The components pieces are Journals&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Journals(...) {
   fun loadActiveIds(): List&amp;lt;String&amp;gt; {...}
   fun loadJournalWithArticles(id: String, articleCount: Int): Journal? {...}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the JournalIndexer&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class JournalIndexer(...) {
   fun createIndex() {...}
   fun index(journal: JournalJson) {...}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The final step is to:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;create the index&lt;/li&gt;
  &lt;li&gt;load the active ids&lt;/li&gt;
  &lt;li&gt;remove some that are excluded&lt;/li&gt;
  &lt;li&gt;pass the remainder to loadJournalWithArticles&lt;/li&gt;
  &lt;li&gt;then pass the returned Journals to the JournalIndexer.index().&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And we should survive exceptions, and loadJournalWithArticles may return null (no such journal), but the indexer can’t index null. And it would be nice to keep track of how far we’ve got, and what worked and what didn’t.&lt;/p&gt;

&lt;p&gt;We’re writing a class called IndexRefresher.&lt;/p&gt;

&lt;h1 id=&quot;mocking&quot;&gt;Mocking&lt;/h1&gt;

&lt;p&gt;Pulling in JMock wasn’t too painful, but my pair and I did argue quite a bit more about the form of the test. This is what it ended up looking like, after maybe half a day, plus a little more playing with how to express expectations in Kotlin.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class IndexRefresherTest {

   @Rule @JvmField val mockery = JUnitRuleMockery()

   val progress = mockery.mock(IndexRefresher.Progress::class.java)
   val refresher = IndexRefresher(99, progress)

   val indexer = mockery.mock(ICanIndexJournals::class.java)
   val journals = mockery.mock(ITellYouAboutJournals::class.java)

   val journal1 = Journal(&quot;1&quot;, &quot;title&quot;, null, null, emptyList(), 0.0, AccessType.OPEN_ACCESS, true, null)
   val journal2 = Journal(&quot;2&quot;, &quot;title&quot;, null, null, emptyList(), 0.0, AccessType.OPEN_ACCESS, true, null)

   @Test fun indexes() {
       mockery.expecting {
           givenActiveJournalIds(
               &quot;1&quot; to returnValue(journal1),
               &quot;2&quot; to returnValue(journal2))

           oneOf(progress).reset(2)
           oneOf(indexer).createIndex()

           oneOf(indexer).index(JournalJson(journal1))
           oneOf(progress).indexed(journal1)

           oneOf(indexer).index(JournalJson(journal2))
           oneOf(progress).indexed(journal2)
       }
       refresher.refresh(journals, indexer, emptySet())
   }

   @Test fun skips_excluded_journals() {
       mockery.expecting {
           givenActiveJournalIds(
               &quot;1&quot; to returnValue(journal1),
               &quot;2&quot; to returnValue(journal2))

           oneOf(progress).reset(1)
           oneOf(indexer).createIndex()

           never(indexer).index(JournalJson(journal1))
           never(progress).indexed(journal1)

           oneOf(indexer).index(JournalJson(journal2))
           oneOf(progress).indexed(journal2)
       }
       refresher.refresh(journals, indexer, setOf(&quot;1&quot;))
   }

   @Test fun skips_not_found_journals() {
       mockery.expecting {
           givenActiveJournalIds(
               &quot;1&quot; to returnValue(null),
               &quot;2&quot; to returnValue(journal2))

           oneOf(progress).reset(2)
           oneOf(indexer).createIndex()

           never(indexer).index(JournalJson(journal1))
           oneOf(progress).noJournal(&quot;1&quot;)

           oneOf(indexer).index(JournalJson(journal2))
           oneOf(progress).indexed(journal2)
       }
       refresher.refresh(journals, indexer, emptySet())
   }

   @Test fun reports_exceptions_and_continues() {
       mockery.expecting {
           val x = RuntimeException(&quot;oops&quot;)

           givenActiveJournalIds(
               &quot;1&quot; to throwException(x),
               &quot;2&quot; to returnValue(journal2))

           oneOf(progress).reset(2)
           oneOf(indexer).createIndex()

           never(indexer).index(JournalJson(journal1))
           oneOf(progress).exception(&quot;1&quot;, x)

           oneOf(indexer).index(JournalJson(journal2))
           oneOf(progress).indexed(journal2)
       }
       refresher.refresh(journals, indexer, emptySet())
   }

   private fun JUnitRuleMockery.expecting(block: MyExpectations.() -&amp;gt; Unit) {
       this.checking(MyExpectations().apply(block))
   }

   inner class MyExpectations : Expectations() {
       fun givenActiveJournalIds(vararg idResultPairs: Pair&amp;lt;String, Action&amp;gt;) {
           allowing(journals).loadActiveIds()
           will(returnValue(idResultPairs.map { it.first }))
           idResultPairs.forEach { pair -&amp;gt;
               allowing(journals).loadJournalWithArticles(pair.first, 99)
               will(pair.second)
           }
       }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here’s the implementation.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class IndexRefresher(private val articleCount: Int, private val progress: Progress) {

   interface Progress {
       fun reset(total: Int)
       fun indexed(journal: Journal)
       fun noJournal(id: String)
       fun exception(id: String, x: Exception)
   }

   fun refresh(journals: ITellYouAboutJournals, indexer: ICanIndexJournals, excludedIds: Set&amp;lt;String&amp;gt;) {
       val idsToProcess = journals.loadActiveIds().filterNot { excludedIds.contains(it) }
       progress.reset(idsToProcess.size)

       indexer.createIndex()

       idsToProcess.forEach { journalId -&amp;gt;
           try {
               val journal = journals.loadJournalWithArticles(journalId, articleCount)
               if (journal != null) {
                   indexer.index(JournalJson(journal))
                   progress.indexed(journal)
               } else {
                   progress.noJournal(journalId)
               }
           } catch(x: Exception) {
               progress.exception(journalId, x)
           }
       }
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h1 id=&quot;comparing-the-code&quot;&gt;Comparing the Code&lt;/h1&gt;

&lt;p&gt;Whilst the algorithm is identical between both implementations, it’s instructive to look at the detail differences.&lt;/p&gt;

&lt;p&gt;Most obviously the mock-generated version has an abstraction for &lt;code&gt;Progress&lt;/code&gt;, while in the approved version, the progress seam is introduced by overriding the &lt;code&gt;println&lt;/code&gt; method. This forces the implementation to be an &lt;code&gt;open&lt;/code&gt; class - in Java you wouldn’t notice this, but in Kotlin classes are &lt;code&gt;final&lt;/code&gt; by default (probably my biggest beef with the language). The &lt;code&gt;Progress&lt;/code&gt; interface is undoubtedly nicer than the plain-old-println in the approved version, and a consequence of being made to think about the relationship between the refresher and reporting progress while we were writing the spec in the test. We could have introduced the interface in the approved version, but didn’t have to in order to test it, so we came down on the side of pragmatism. This pragmatism also explains the nasty hiding of the &lt;code&gt;println&lt;/code&gt; global function by a method - obviously we were originally just printing to the console, and the override gave us a dirty way to capture that output into the approved file.&lt;/p&gt;

&lt;p&gt;More subtly, while both versions have an interface, &lt;code&gt;ICanIndexJournals&lt;/code&gt;, to allow us to introduce selectable indexing behaviour, the mocked version introduces &lt;code&gt;ITellYouAboutJournals&lt;/code&gt;, whereas the approved version is able to use the production &lt;code&gt;Journals&lt;/code&gt; implementation. This introduction of interfaces just to facilitate testing is common, if controversial. Mockista’s argue that it introduces seams that better express the structure of the problem, and can aid extensibility and reuse. Countering that is the introduction of complexity that is not actually solving todays’ problem, and the difficulty finding a different name for the interface to a thing from its default implementation - should it be  &lt;code&gt;IIndexer&lt;/code&gt; / &lt;code&gt;Indexer&lt;/code&gt; or &lt;code&gt;Indexer&lt;/code&gt; / &lt;code&gt;IndexerImpl&lt;/code&gt;. Since discovering the &lt;code&gt;IAmAnInterfaceNameThatTellsYouWhatIDo&lt;/code&gt; convention I’m more delighted by the opportunity for whimsy than bugged by the two names, but you may disagree.&lt;/p&gt;

&lt;p&gt;By the way, if you’re wondering why both versions pass the &lt;code&gt;journals&lt;/code&gt; and &lt;code&gt;indexer&lt;/code&gt; into the &lt;code&gt;refresh&lt;/code&gt; method rather having them as fields, it’s because in the actual code we want to rebuild them from scratch when we reindex (once a month or so) to avoid having any state lying around between runs.&lt;/p&gt;

&lt;h1 id=&quot;comparing-the-tests&quot;&gt;Comparing the Tests&lt;/h1&gt;

&lt;p&gt;If the implementation is largely the same, the tests differ wildly:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The mock test runs very much faster&lt;/li&gt;
  &lt;li&gt;The approvals test combines all the things that it is verifying into one test, the mock test shows what happens&lt;/li&gt;
  &lt;li&gt;The details of the behaviour of the refresher are hidden inside in the approved file, and even then require interpretation. The mock makes the behaviour clear in the test.&lt;/li&gt;
  &lt;li&gt;The mock test is able to show the behaviour of the code in the face of exceptions, the approvals test doesn’t. I suppose it could, but it would complicate things quite a bit.&lt;/li&gt;
  &lt;li&gt;The approvals test exercises the Journals code against the real API, at least on its first run.&lt;/li&gt;
  &lt;li&gt;The approvals test relies on HTTP caching magic, the mock test on JMock magic.&lt;/li&gt;
  &lt;li&gt;The mock test took and implementation took half a day, perhaps longer than expected because I was working with a new pair. The approvals test and implementation took maybe an hour, but would have been longer had the HTTP caching not already been in place.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You’ll have probably made up your mind which you prefer by now, but I’m still on the fence. The JMock test seems a lot more valuable in showing the behaviour of the code, but it doesn’t tell you anything you couldn’t get by looking at the actual implementation for 2 minutes. It will tell you if a change to that implementation changes its behaviour, but because it’s a strict unit test, won’t tell you if changes to any of its collaborators will change its behaviour. The approvals test is pretty useless at telling you what the code does, but that doesn’t matter if you can work it out in 2 minutes, and it will fail if changes to &lt;code&gt;Journals&lt;/code&gt; or some of its dependencies change what it tries to index.&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Mocks v Approvals Tests Part 1</title>
   <link href="http://0.0.0.0:4000/mocks-v-approvals-tests-part1.html"/>
   <updated>2016-04-23T00:00:00-05:00</updated>
   <id>http://0.0.0.0:4000/mocks-v-approvals-tests-part1</id>
   <content type="html">&lt;p&gt;Aka: Test Driven Design v Test Driven Development&lt;/p&gt;

&lt;h1 id=&quot;context&quot;&gt;Context&lt;/h1&gt;

&lt;p&gt;In my current gig at &lt;a href=&quot;http://springernature.com&quot;&gt;Springer Nature&lt;/a&gt; (&lt;a href=&quot;https://www.linkedin.com/jobs/springer-science-business-media-jobs&quot;&gt;we’re hiring :-&lt;/a&gt;) I’ve been TDDing some Kotlin code to index data from a web service into Elastic Search. All the pieces are in place, they just need to be wired together and invoked.&lt;/p&gt;

&lt;p&gt;The component pieces are Journals&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class Journals(...) {
   fun loadActiveIds(): List&amp;lt;String&amp;gt; {...}
   fun loadJournalWithArticles(id: String, articleCount: Int): Journal? {...}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and the JournalIndexer&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class JournalIndexer(...) {
   fun createIndex() {...}
   fun index(journal: JournalJson) {...}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The final step is to:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;create the index&lt;/li&gt;
  &lt;li&gt;load the active ids&lt;/li&gt;
  &lt;li&gt;remove some that are excluded&lt;/li&gt;
  &lt;li&gt;pass the remainder to loadJournalWithArticles&lt;/li&gt;
  &lt;li&gt;then pass the returned Journals to the JournalIndexer.index().&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There are complications of course, we should survive exceptions, and loadJournalWithArticles may return null (no such journal), but the indexer can’t index null. And it would be nice to keep track of how far we’ve got, and what worked and what didn’t. Let’s write a class called IndexRefresher.&lt;/p&gt;

&lt;h1 id=&quot;but-first-a-test&quot;&gt;But First, A Test&lt;/h1&gt;

&lt;p&gt;Whether this is T.D.Development or T.D.Design, I should write a test first. We probably don’t want to hit the web service API or Elastic Search with a unit test, so my first instinct is to reach for JMock. But as it happens this little service hasn’t needed JMock yet, so let’s see how we get on without it.&lt;/p&gt;

&lt;h1 id=&quot;approvals-testing&quot;&gt;Approvals Testing&lt;/h1&gt;

&lt;p&gt;What we &lt;em&gt;do&lt;/em&gt; have is an HttpFetcher abstraction that allows us to replay previous responses and an Approvals Testing library. We can use the former to use our actual implementation of Journals, and the latter to lock down the progress reporting and indexed data. The test takes quite a bit of setup, but the first time we run it we will hit the real data and can approve the results from processing it.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;class IndexRefresherApprovalsTest {

   @Rule @JvmField val approver = ApprovalsRule.fileSystemRule(&quot;src/test/java&quot;)

   val transcript: Transcript by lazy { approver.transcript() }
   val cacheDir = File(&quot;src/test/resources/refresher-cache&quot;)
   val articles = Articles(ContentAPI(CachingHttpFetcher(File(cacheDir, &quot;articles-http-cache&quot;), httpFetcher)))
   val journals = Journals(ContentAPI(CachingHttpFetcher(File(cacheDir, &quot;journals-http-cache&quot;), httpFetcher)), articles)

   val refresher = object : ScratchIndexRefresher(5) {
       override fun println(message: String?) {
           transcript.appendLine(message)
       }
   }

   @Test fun indexes() {
       val indexer = object : ICanIndexJournals {
           override fun createIndex() {
               transcript.append(&quot;Index created&quot;)
           }
           override fun index(journal: JournalJson): Id&amp;lt;JournalJson&amp;gt; {
               transcript.appendFormatted(journal, jsonFormatter).endl()
               return Id(journal.id)
           }
       }

       val exclusions = readExcludedJournalIdsFrom(journals.javaClass, &quot;/excluded-journals.csv&quot;)
       refresher.refresh(journals, indexer, exclusions)
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The implementation&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;open class ScratchIndexRefresher(private val articleCount: Int) {

   fun refresh(journals: Journals, indexer: ICanIndexJournals, excludedIds: Set&amp;lt;String&amp;gt;) {
       val idsToProcess = journals.loadActiveIds().filterNot { excludedIds.contains(it) }
       println(&quot;Starting - total journals = ${idsToProcess.size}&quot;)
       idsToProcess.forEach { journalId -&amp;gt;
           try {
               val journal = journals.loadJournalWithArticles(journalId, articleCount)
               if (journal != null) {
                   indexer.index(JournalJson(journal))
                   println(&quot;Indexed $journalId (${journal.title})&quot;)
               } else {
                   println(&quot;No data for journalId $journalId&quot;)
               }
           } catch(x: Exception) {
               kotlin.io.println(&quot;Exception processing journal ${journalId}, ${x.message}&quot;)
           }
       }
   }

   open fun println(message: String?) = kotlin.io.println(message)

}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The file we approve to pass the test next time looks like this&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Starting - total journals = 2976
No data for journal Id 41406
{
 &quot;id&quot; : &quot;299&quot;,
 &quot;name&quot; : &quot;Plant Cell Reports&quot;,
 ...
}
Indexed 299 (Plant Cell Reports)
No data for journal Id 13646
{
 &quot;id&quot; : &quot;12914&quot;,
 &quot;name&quot; : &quot;BMC International Health and Human Rights&quot;,
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s suspend judgement of this code and test until we see what a mocking approach comes up with - it’s &lt;a href=&quot;/mocks-v-approvals-tests-part2.html&quot;&gt;after the break&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 

</feed>
