I'm Damien Le Berrigaud, Software Engineer for Pivotal Software. I like working with Kotlin, F#, Elm, Android, iOS (Swift or Objective-C), Go... I've had previous experiences in Ruby and .NET.

That's a lot of technologies that I got to work with while working at Pivotal Labs and in my previous jobs. In order to keep up-to-date, I keep rebuilding this website.

This version is written in F# for the frontend and for the backend running on the .NET Core platform. The source code is entirely available on my github.

You can choose to follow multiple of my feeds, on a single page, by using the menu at the top of the page.

January 25 '22 @ 19:37

People that try to apologize should explain why they were wrong, not why they thought it was right. How do we know… https://t.co/BqjFNhSkud

January 19 '22 @ 01:22

I don’t like it when people are called talented when they have clearly spent hundreds of hours honing their skills.… https://t.co/eCY7VAVhZg

January 15 '22 @ 14:33

J'aurais jamais eu mon master si des egoïstes comme ça écrivaient les lois. Votez. https://t.co/Mp7SAJAgML

January 07 '22 @ 15:33

Every once in a while you hear the joke of the software engineers that spent a whole day figuring out that they wer… https://t.co/mkVFQ64onx

January 07 '22 @ 03:39

Having drinking water from the tap is underrated. It’s back!

January 07 '22 @ 03:24

Re-watching “Miracle workers”, it’s currently HBO. Hilarious TV series with Steve Buscemi, Daniel Radcliffe, Karan… https://t.co/3uPLBfTUQ7

January 03 '22 @ 02:00

Been watching Ted Lasso. Should be a required watch to anyone than needs to work on their empathy… that is anyone really.

December 31 '21 @ 02:33

Evacuated our house in Louisville earlier this afternoon. Hoping the fires won’t reach it. We are safe though.

December 30 '21 @ 15:07

Frontend validations do not help with having consistent data. Any validations that you have on your frontend but no… https://t.co/FzlBfmBKQa

Error handling in Kotlin and any modern static type system

August 16 '18 @ 05:15

This article is about leveraging a technique called Railway Oriented Programming, in Kotlin. It is extensively documented in functional languages, particularly well in the F# community. So I’m going to try to explain how to implement some of it in Kotlin.

Some background

Having written my fair share of Java, Go, Ruby… I’ve seen quite a few different paradigms for error handling.

In Ruby, one would return different types based on the error status of a given function. We would (for example) use symbols to indicate the specific type of error that was reached (e.g. :not_found, :connection_failed…).

It then becomes the responsibility of the consumer of the function to figure out the different possible results. The programmer ends up having to read the tests for the function, relying on the documentation being accurate, or reading through the code of the function itself.

In Java, we use exceptions for indicating the function is not successful. Non-Runtime exceptions have to be caught and handled, which ends up with a lot of code like this -

try {
} catch (IOException e) {
    throw new RuntimeException(e);

And that obviously can result with a lot of run-time problems…

In Go, a function can have multiple return values. The convention is to return an error and the value that is wanted. Then the programmer has to check for the error before continuing the execution. This results in code similar to this -

value, err := myFunction()
if err != nil {
    return nil, err

Unfortunately, it can be very easy to forget to handle the error case. The compiler will be just fine if we forget to look at the err variable or if we don’t assign it. Also this has the unfortunate side effect of spreading the “happy path” code in many small chunks of code separated by error checks.

Enter discriminated unions

Although I am far from being an expert (really far), I have been toying around with some functional languages lately. In particular, I like the simplicity of Elm and F#, but I’m looking forward to learning more about advanced functional programming with Haskell and/or Scala eventually.

Regardless, in all these languages there is the concept of a discriminated union in F# or union type in Elm. It allows the programmer to represent a type that can have one or many states that can each have their own complexity. Think about it as an “enum on steroids”! Actually Rust and Swift enums are union types.

For example in F# you can create an Optional type like this -

type Optional<'a> =
    | Just of 'a
    | Nothing

That means that a value of type Optional<string> can either have the value Nothing or it can be Just and would contain something of type string. This Optional type is a great way of representing the potential absence of a value, and it helps avoiding null pointer exceptions. Now you might say “but Kotlin already has a way to avoid null pointer exceptions built-in”, and you are right. So let’s look at a type that is built-into F#.

type Result<'success, 'error> =
    | Success of 'success
    | Error of 'error

If I write a function that returns something of type Result<User, ErrorMessage> then I know that I will either get a Success back containing a User or I will get an Error back and it contains an ErrorMessage. And the F# compiler would ask me to handle both cases.

This is actually very similar to a type that you will find in most functional languages, Either. It exists in Scala and in Haskell.

And now you might say “but does Kotlin even have any way to do that at all?!”, and you are in luck, because it does!

Enter Kotlin’s sealed classes

The same type that we just represented in F# can be represented as follows in Kotlin.

sealed class Result<T, E>

data class Success<T, E>(val value: T): Result<T, E>()

data class Error<T, E>(val value: E): Result<T, E>()

And you could use the type like this:

data class User(val name: String)
data class ErrorMessage(val message: String)

fun myFunction(): Result<User, ErrorMessage> =

when (val result = myFunction()) {
    is Success -> println("Success we got the user ${result.value.name}")
    is Error -> println("Oops we got a failure ${result.value.message}")

Now this is very basic but already usable, and the compiler will require that we do match both cases: Success and Error. It may seem a bit tedious to always have to match on result after calling the function. After all, the extra boilerplate is why Java developers tend to use a lot of RuntimeExceptions instead of having to catch or re-throw them all over the place.

So let’s add a few functions to the Result class to help handle it.

sealed class Result<T, E> {
    abstract fun <NewT> map(mapping: (T) -> NewT): Result<NewT, E>
    abstract fun <NewT> flatMap(mapping: (T) -> Result<NewT, E>): Result<NewT, E>
    abstract fun <NewE> mapFailure(mapping: (E) -> NewE): Result<T, NewE>
    abstract fun <NewE> flatMapFailure(mapping: (E) -> Result<T, NewE>): Result<T, NewE>
    abstract fun orElse(other: T): T
    abstract fun orElse(function: (E) -> T): T

The full implementation can be found as a Gist on my Github.

With these functions you will be able to write code that handles errors very simply and concisely. For example,

fun fetchUsers(): Result<List<User>, ErrorMessage> =
    buildRequest("GET", "http://example.com/api/users")
        .flatMap { it.parseJson<UserListJson>() }
        .map { it.users }

In this example, I executed an HTTP request using a function that returns a Result then I parsed the response if the Result was a Success. The parsing is also a function that returns a Result so I used flatMap. Finally I return the list of Users from the parsed UserListJson.

At no point in that function did I have to handle the error branches (because my functions are always using ErrorMessage for the failure case).

This makes for code that is a lot easier to maintain. The compiler is going to do most of the heavy lifting for us.

This is Railway Oriented Programming (I highly recommend reading that article).

I would encourage you to try and use this style of programming more and more if you have the privilege of using a language that offers this kind of feature. If you are using any external library that throws exceptions, make sure to write some small wrapper functions that will instead return a Result type.

Enjoy your exception free codebase!

Testing Kotlin with a custom DSL for Aspen

July 13 '16 @ 06:34

Aspen Logo

Where that feature came from

When I started working on Aspen, I was focusing on only a few things: I want an easy way to regroup my tests for a given function, and I want to be able to name my tests with a simple sentence but I don’t want to have to name my tests. That lead to version 1.0.

Then came Spring integration, version 1.1. Then we started talking to more people to see what they wanted, and it became quickly obvious that a very simple DSL was not going to be enough for some. So I started working on another DSL that would allow nesting of the tree structure, like rSpec does. This lead to version 1.2.

During the creation of that second DSL, I tried to figure out what was the right abstraction for it. It became obvious that we are building a tree structure and running that. So now I’m going to show you how to create your own DSL that builds a tree structure for Aspen.

Building a TestTree

The goal of the DSL is to build a TestTree that can then be run by the TestTreeRunner from Aspen. For example, with the built-in DSL, the following code…

class MyTests: Test({

    describe("foo") {
        test("a") {


        test("b") {


    describe("bar") {
        test("c") {


…would build the following structure.

Test Tree Structure

The TestTree Interface

An Aspen DSL implements the TestTree Interface.

interface TestTree {
    fun readTestBody()
    fun getRoot(): TestBranch

The readTestBody function is the one that is supposed to evaluate the body of the tests and build the tree structure, thus making the root available. It is invoked at a particular time in the SpringTestTreeRunner for instance, the default TestTreeRunner invokes it as soon as it needs to browse the tree.

The getRoot function is more obvious, it returns the first branch of your Tree.

A TestBranch has children and optional before and after blocks. Its children can be of type TestBranch or TestLeaf. A TestLeaf represents an actual test, it has a block of code to execute and can have a focused flag.

All the code for the TestTree is in a single file: https://github.com/dam5s/aspen/blob/master/libraries/aspen/src/main/kotlin/io/damo/aspen/TestTree.kt

The Test class

Let’s start with the easy part, implementing the TestTree interface:

open class Test : TestTree {
    private val root = TestBranch.createRoot()
    private val body: Test.() -> Unit

    constructor(body: Test.() -> Unit) {
        this.body = body

    override fun getRoot() = root

    override fun readTestBody() {

This is an open class that is run with the TestTreeRunner and implements TestTree. The root is created with TestBranch.createRoot, creating a branch without parent, without name… The body is an extension function for the class itself, this is the block of code that will contain your tests and build the TestTree structure, it is evaluated in the readTestBody function.

Now you can start adding some functions that will help you build the tree.

This will allow specifying the before and after block:

fun before(block: () -> Unit) {
    root.before = block

fun after(block: () -> Unit) {
    root.after = block

This will add a test at the root level:

fun test(name: Any = "unnamed test", block: () -> Unit) {
    root.addChildLeaf(name.toString(), block)

Now in order to add branches that do not allow nesting, we have to create a function that will take an extension function for a different type. If it was for the same type, then we would be able to call that same function over and over.

fun describe(name: Any, block: TestDescription.() -> Unit) {
    val newBranch = root.addChildBranch(name.toString())

The TestDescription only allows adding tests:

class TestDescription(private val branch: TestBranch) {
    fun test(name: String = "unnamed test", block: () -> Unit) {
        branch.addChildLeaf(name, block)

And that’s it! From that point you can start making your DSL even smarter.

For instance, I have been working on making a DSL for nicer table based tests. You can see its first implementation on Github. It would allow for writing a test like this:

class MathTest : Test({

    class MaxData(context: String, val a: Int, val b: Int, val c: Int)
        : TestData(context)

    val testData = listOf(
        MaxData("when equal", 2, 2, 2),
        MaxData("when a is greater", 3, 1, 3),
        MaxData("when b is greater", 3, 4, 4)

    tableTest(testData) {
        test {
            assertThat(Math.max(a, b), equalTo(c))

But it is still a work in progress, as I still need to figure out exactly how I want my test to look like (that test block does not look useful for instance).

I hope this convinced you that it’s very simple to write your own type safe DSL for testing with Aspen. Let me know what you think about it!

Kotlin testing with Aspen and Aspen Spring

July 06 '16 @ 03:14

TL;DR — Aspen 2.0 is out, check it out: https://github.com/dam5s/aspen

How I got into Kotlin

I started looking at Kotlin around release M9, it was quite a few months before it was released as 1.0, but it was already very usable. Kotlin promised easy integration with your Java code, running on the Java 6 VM and a lot of features that make the code a lot nicer to work with.

Having worked with Java for a couple years with some of our clients, I was really excited to get rid of the verbosity and keep the things I like in Java: a good build system (Gradle), easy to build modular applications, a decent type system (that gets improved a lot by Kotlin), and a huge ecosystem with mature libraries.

Our first production project for a client was using Kotlin M12 for an Android application. The experience was great, the client developers were former C# developers. They loved the language, and despite a few quirks here and there, we shipped it by the time Kotlin M13 was released. A few weeks later, Kotlin 1.0 was released.

Now I have been through a couple more projects with Kotlin and I would advise any Java developer out there to look into it. It’s easy to get started with, and you can introduce it in your existing projects without pain.

Why I decided to create Aspen

I have been really enjoying the simplicity of Java unit tests using JUnit. Its simplicity encourages you to write simple tests that are easy to read. Using only one “@Before” annotated function encourages you to make each test readable from top to bottom without having to jump around.

The only thing I really miss from my Ruby days was being able to write a short sentence to describe my test. With JUnit, I would name tests following this pattern:

public void testMyFunction              // testing the happy path
public void testMyFunction_WhenInput... // testing another context

Some developers would also describe the expected outcome in the function name. I do not do that because I want to encourage developers in my team to name variables and write assertions that talk for themselves. Also I do not want to have yet another comment that can get out of sync easily.

Kotlin allowing to create type safe DSLs, I decided to write a DSL for testing. It is inspired by RSpec and Spek, but it is a lot simplified and easy to extend with your own DSL if you would like.

Here comes Aspen

An Aspen test looks like this:

class PersonTestExample : Test({
    describe("#fullName") {
        test {
            val person = buildPerson(
                firstName = "Jane",
                lastName = "Doe"
            assertThat(person.fullName(), equalTo("Jane Doe"))

        test("with a middle name") {
            val person = buildPerson(
                firstName = "John",
                middleName = "William",
                lastName = "Doe"
            assertThat(person.fullName(), equalTo("John W. Doe"))

    describe("#greeting") {
        test {
            val person = buildPerson(
                firstName = "Jane",
                lastName = "Doe"
            assertThat(person.greeting(), equalTo("Greetings Jane!"))

Output from running the test above in IntelliJ IDEA.

With the help of a few colleagues (Joe, Jack, Mike G, Travis, Nathan, Alex… thanks guys!), we wrote Aspen. It’s a really simple DSL that makes unit tests easier to organize, and it’s built on top of JUnit.

Spring Integration

A big requirement for us to use a testing framework: it has to work with Spring. Most of the tests we write with Spring are pure unit tests, so that already just works. But we also have a few tests that require us to use the Spring test runner in order to spin up the server and run some higher level tests.

Thankfully the Spring team has done a great job at abstracting the way the Spring runner work. It’s been very easy to write our own runner for Spring that reuses the code by the Spring team.

A test with Aspen Spring can look like this:

class SpringApplicationTestExample : Test({

  val message: String = inject("myMessage")
  val port = injectValue("local.server.port", Int::class)
  val client = OkHttpClient()

  test("GET /hello") {
    val request = Request.Builder()
    val response = client.newCall(request).execute()

    val body = response.body().string()

    assertThat(body, equalTo("""{"hello":"world"}"""))
    assertThat(body, equalTo("""{"hello":"$message"}"""))

  test("GET /world") {

Getting Aspen and Aspen Spring

Instructions for setting up Aspen and Aspen Spring are on my Github.