DEV Community

Cover image for Gang of Four Patterns in Kotlin

Gang of Four Patterns in Kotlin

Lovis on June 01, 2017

Kotlin is getting more and more relevant. How would common design patterns implemented in Kotlin look like? Inspired by Mario Fusco's Talk/Blog pos...
Collapse
 
mariofusco profile image
Mario Fusco

Great post, I just have one note: for what regards the Decorator example, you're using extension methods, which is a very desirable feature of Kotlin and other languages like C#. That's nice, but the point of the corresponding example in my Java 8 implementation was a bit different and probably more fundamental. The Decorator pattern as demonstrated in GoF is just a very convoluted way to achieve functions composition. Using functions composition, which is not a specific language feature, but a corner stone of functional programming, and then available in any language with a minimal functional support including Java 8, you can achieve the same result in a more elegant way. Conversely what you did is reimplementing the Decorator pattern literally and in its original form, only in a more concise way using Kotlin's better expressiveness. Both solutions are valid, but still I believe that the one using function composition is more functional-ish, general and possibly even easier to read and to implement.

Collapse
 
marioariasc profile image
Mario Arias

My library (funKTionale) implements function composition for Kotlin (among other goodies) github.com/MarioAriasC/funKTionale...

Currently working on a blog post series covering many features

Collapse
 
qwertukg profile image
Daniil Rakhmatulin

its hard to read infix fun in this case

Collapse
 
lovis profile image
Lovis

Really looking forward to your posts!

Thread Thread
 
lovis profile image
Lovis • Edited

Here it is, if anyone is interested and drops by:
hackernoon.com/funktionale-functio...

Collapse
 
lovis profile image
Lovis

Hey Mario, first of all: thanks for your kind words!
It's definitely true that function composition would be the better solution here. I used extensions because it's "pure" Kotlin. I didn't want to copy your examples and solutions, either. Thought that would be boring :-)

Collapse
 
qwertukg profile image
Daniil Rakhmatulin • Edited

Really good post. short and clean - like as a Kotlin style ;)
But i think builder could be opened more. Your example is good, but i mean the using of builder is much more then just setting of a properties. Most interesting example, is then u want to pass some code like as parameter. Something from my DSL for selenium SeleniumBuilder:

inline fun <T : WebDriver> driver(driver: T, init: T.() -> Unit) {
    try {
        driver.init()
    } finally {
        driver.close()
    }
}

Or more colorful example, like as u show, if u want to calc execution time of some code:

inline fun calcExecTime(init: () -> Unit): Float {
    val start = System.nanoTime()
    init()
    return (System.nanoTime() - start) / 1000000000F
}
val resultTime = calcExecTime {
    // do anything here
}
Collapse
 
sorokod profile image
David Soroko

Using apply for post constructor changes is nice but I wouldn't call it a builder. With the approach you are describing an instance is created first, with empty constructor, and then modified in the apply{} block. This means that

  1. Default values are required

  2. It is not possible to ensure that an instance exists only if the parameters are valid

Collapse
 
lovis profile image
Lovis

thank you!

yeah, those type save builders / DSLs are nice. But they are a topic on their own, and and wanted to keep it "basic" :-)

I would not consider calcExecTime a builder, since it does not create anything.

btw a method like this already exists in the standard lib - its called measureTimeMillis :-)

Collapse
 
qwertukg profile image
Daniil Rakhmatulin

actually yes, its build nothing) sorry for disorientation, but I want to show many other features, who can be provided by lambda with receiver.

Collapse
 
anitas3791 profile image
Anita Singh

Loved this post! I just started using Kotlin in our Android app two months ago and feel that I am writing Java-ey Kotlin sometimes. These are great patterns to keep in mind, looking forward to using them!

Collapse
 
geraldcroes profile image
geraldcroes

I found your article while I was looking for patterns examples in Kotlin ... loved it (and loved its [more advanced] sequel)

The factory was missing, so (even if it's quite straight forward) I've written an article about it.

I wonder if you have other (better) solutions.
medium.com/the-coding-matrix/kotli...

Collapse
 
uweschaefer profile image
Uwe Schaefer

Minor typo:

Dictionary.addWord(word, "an awesome programming language created by JetBrains")

should be

Dictionary.addDefinition(word, "an awesome programming language created by JetBrains")

Collapse
 
lovis profile image
Lovis

Thanks, Uwe! Fixed.

Collapse
 
kenkyee profile image
Ken Yee

For the Builder pattern, you can also use a constructor w/ named params...seems more Kotlin idiomatic IMHO...

Collapse
 
lovis profile image
Lovis • Edited

I agree for this particular example, but consider a class with more properties.
You generally don't want a constructor (or any other method) with five or more parameters.

The builder can also do more than just building the object. E.g. validating correct property-combinations, which is not something you should do inside a constructor.

Collapse
 
programmerr47 profile image
Michael

I think one of the problems with your approach is theoretically possibility to have broken data, since constuction of object is separated from setting up field.

Approach with naming constructor parameters or more stable and looks like builder, since all preparations are happen in constructor of object. And if it will fail, you just will not receive a new object.

Thread Thread
 
lovis profile image
Lovis

Sure, but separating construction from representation is the whole point of the Builder pattern.

Collapse
 
gabin278 profile image
Andrey Derkach

Thanks! Great article. Looking forward for the next useful ones

Collapse
 
nicc_fsc profile image
Jeremy Feng

I am a game programmer in China. In my country, few people use Kotlin for programming, What do people think of Kotlin in your country? Do many people use it to develop Android?

Collapse
 
lovis profile image
Lovis

It's still a niche language here in Germany.
Most people who use it use it for Android.
I'm trying to change that, though. E.g. I founded the Kotlin User Group Hamburg, to "spread the word" πŸ˜‰

Collapse
 
ben profile image
Ben Halpern

I'm really enjoying your Kotlin posts. I'm relying on them to keep up as I consider getting into Kotlin, thanks a lot.

Collapse
 
lovis profile image
Lovis

Thank you! Great to hear that!