SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Design
Patterns
with
Kotlin
Alexey Soshin, June 2019
whoami
● Principal Developer @Wix
● Former Software Architect @Gett
● Author of “Hands-on Design Patterns with Kotlin” book
● StackOverflow junkie, top 2% this year
● Occasional Medium writer
● Currently living in London
Intro
● “Design Patterns” by “Gang of Four” book was written back in ‘92. This is the only edition
of the book. All examples in the book are either in C++ or SmallTalk
● Somebody once said that “design patterns are workarounds for shortcomings of
particular language”. But he was fan of Lisp, so we can disregard that saying
● Disclaimer: all your favorite design patterns, including Singleton, will work in Kotlin as-is.
Still, there are often better ways to achieve the same goal
Kotlin
● Programming language from JetBrains, authors of IntelliJ IDE
● Runs on JVM (but can also be transpiled into JavaScript or platform native code)
● Still more concise than Java 12
● Typesafe (hi, Groovy!)
● Null-safe
● Pragmatic (hi, Scala!)
Singleton
“Ensure a class has only one instance, and provide a global point of access to it.”
public final class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
In Java:
volatile
synchronized
instance
static
private static
Singleton - continued
object Singleton
Taken directly from Scala
CounterSingleton.INSTANCE.increment();
When called from Java, instead of usual .getInstance() uses INSTANCE field
CounterSingleton.increment()
Very concise usage syntax:
In Kotlin:
Builder
“Allows constructing complex objects step by step”
ElasticSearch API, for example, just LOVES builders...
client.prepareSearch("documents")
.setQuery(query(dressQuery))
.addSort(RANK_SORT)
.addSort(SEARCHES_SORT)
.get()
Builder - continued
In Kotlin, often can be replaced with combination of default parameters and .apply()
function
data class Mail(val to: String,
var title: String = "",
var message: String = "",
var cc: List<String> = listOf(),
var bcc: List<String> = listOf(),
val attachments: List<java.io.File> = listOf()) {
fun message(m: String) = apply {
message = m
} // No need to "return this"
}
val mail = Mail("bill.gates@microsoft.com")
.message("How are you?").apply {
cc = listOf("s.ballmer@microsoft.com")
bcc = listOf("pichais@gmail.com")
}
Less boilerplate, same readability
Proxy
“Provides a substitute or placeholder for another object”
Decorator and Proxy have different purposes but
similar structures. Both describe how to provide a
level of indirection to another object, and the
implementations keep a reference to the object to
which they forward requests.
In Kotlin: by keyword is used for such delegation
val image: File by lazy {
println("Fetching image over network")
val f = File.createTempFile("cat", ".jpg")
URL(url).openStream().use {
it.copyTo(BufferedOutputStream(f.outputStream()))
}.also { println("Done fetching") }
f
}
Iterator
“Abstracts traversal of data structures in a linear way”
class MyDataStructure<T> implements Iterable<T> { ... }
In Java, this is built-in as Iterable interface
Same will work also in Kotlin
class MyDataStructure<T>: Iterable<T> { ... }
Iterator - continued
But in order not to have to implement too many interfaces (Android API, anyone?), you
can use iterator() function instead:
class MyDataStructure<T> {
operator fun iterator() = object: Iterator<T> {
override fun hasNext(): Boolean {
...
}
override fun next(): T {
...
}
}
}
Note the “operator” keyword before the name of the function.
State
“Allows an object to alter its behavior when its internal state changes”
sealed class Mood
object Still : Mood() //
class Aggressive(val madnessLevel: Int) : Mood()
object Retreating : Mood()
object Dead : Mood()
Kotlin sealed classes are great for state management
Since all descendants of a sealed class must reside in the same file, you also
avoid lots of small files describing states in your project
State - continued
Best feature is that compiler makes sure that you check all states when using
sealed class
override fun seeHero() {
mood = when(mood) {
is Still -> Aggressive(2)
is Aggressive -> Retreating
is Retreating -> Aggressive(1)
// Doesn't compile, when must be exhaustive
}
}
override fun seeHero() {
mood = when(mood) {
is Still -> Aggressive(2)
is Aggressive -> Retreating
is Retreating -> Aggressive(1)
is Dead -> Dead // Better
}
}
You must either specify all conditions, or use else block
Strategy
“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets
the algorithm vary independently from the clients that use it.”
class OurHero {
private var direction = Direction.LEFT
private var x: Int = 42
private var y: Int = 173
// Strategy
var currentWeapon = Weapons.peashooter
val shoot = fun() {
currentWeapon(x, y, direction)
}
}
In Kotlin functions are first class citizens.
If you want to replace a method - replace a method, don’t talk.
Strategy - continued
object Weapons {
val peashooter = fun(x: Int, y: Int, direction: Direction) {
// Fly straight
}
val banana = fun(x: Int, y: Int, direction: Direction) {
// Return when you hit screen border
}
val pomegranate = fun(x: Int, y: Int, direction: Direction) {
// Explode when you hit first enemy
}
}
You can encapsulate all available strategies
And replace them at will
val h = OurHero()
h.shoot() // peashooter
h.currentWeapon = Weapons.banana
h.shoot() // banana
This is typesafe (hi, JavaScript!), and you don’t need to implement an interface
Deferred value
Not once I’ve heard JavaScript developers state that they don’t need design patterns in
JavaScript.
But Deferred value is one of the concurrent design patterns, and it’s widely used nowadays
Also called Future or Promise
with(GlobalScope) {
val userProfile: Deferred<String> = async {
delay(Random().nextInt(100).toLong())
"Profile"
}
}
val profile: String = userProfile.await()
In Kotlin provided as part of coroutines library:
Fan Out
“Deliver message to multiple destinations without halting the process”
Producer
Consumer 1 Consumer 2 Consumer 3
“r” “n” “d”
Used to distribute work
Each message delivered to only one consumer,
semi-randomly
Kotlin coroutine library provides
ReceiveChannel for that purpose
fun CoroutineScope.producer(): ReceiveChannel<String> = produce {
for (i in 1..1_000_000) {
for (c in 'a' .. 'z') {
send(c.toString()) // produce next
}
}
}
Fan Out - continued
Consumers can iterate over the channel, until it’s closed
fun CoroutineScope.consumer(id: Int,
channel: ReceiveChannel<String>) = launch {
for (msg in channel) {
println("Processor #$id received $msg")
}
}
Here we distribute work between 4 consumers:
val producer = producer()
val processors = List(4) {
consumer(it, producer)
}
for (p in processors) {
p.join()
}
Fan In
Similar to Fan Out pattern, Fan In relies on coroutines library and channels
“Receive messages from multiple sources concurrently”
fun CoroutineScope.collector(): SendChannel<Int> = actor {
for (msg in channel) {
println("Got $msg")
}
}
Multiple producers are able to send to the same channel
fun CoroutineScope.producer(id: Int, channel: SendChannel<Int>) = launch {
repeat(10_000) {
channel.send(id)
}
}
Fan In - continued
val collector = collector()
val producers = List(4) {
producer(it, collector)
}
producers.forEach { it.join() }
Multiple producers are able to send to the same channel
Outputs:
...
Got 0
Got 0
Got 1
Got 2
Got 3
Got 0
Got 0
...
Summary
● Design patterns are everywhere
● Like any new language (unless it’s Go), Kotlin learns from shortcomings of its
predecessors
● Kotlin has a lot of design patterns built in, as either idioms, language constructs or
extension libraries
● Design patterns are not limited by GoF book
References
https://sourcemaking.com/design_patterns
https://refactoring.guru/design-patterns
https://www.amazon.com/Hands-Design-
Patterns-Kotlin-applications-
ebook/dp/B079P7Q5HX
Question time
Thanks a lot for attending!
Code: https://github.com/AlexeySoshin/KotlinFanInOutAnimation
Keep in touch:
● https://twitter.com/alexey_soshin
● https://stackoverflow.com/users/5985853/alexey-soshin
● https://github.com/alexeysoshin

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Hyuk Hur
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นFinian Nian
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftColin Eberhardt
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherColin Eberhardt
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to KotlinPatrick Yin
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Taehwan kwon
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in JavascriptKnoldus Inc.
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoakleneau
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 

Was ist angesagt? (20)

Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"Let'swift "Concurrency in swift"
Let'swift "Concurrency in swift"
 
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้นคลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
คลาสและการเขียนโปรแกรมเชิงวัตถุเบื้องต้น
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better Together
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
Do
DoDo
Do
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
Intro to ReactiveCocoa
Intro to ReactiveCocoaIntro to ReactiveCocoa
Intro to ReactiveCocoa
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 

Ähnlich wie Design patterns with kotlin

Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#Rohit Rao
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Abu Saleh
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinKai Koenig
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresGarth Gilmour
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++Joan Puig Sanz
 

Ähnlich wie Design patterns with kotlin (20)

Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
React native
React nativeReact native
React native
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with Kotlin
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
A TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS AdventuresA TypeScript Fans KotlinJS Adventures
A TypeScript Fans KotlinJS Adventures
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
Clojure class
Clojure classClojure class
Clojure class
 

Kürzlich hochgeladen

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 

Kürzlich hochgeladen (20)

Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 

Design patterns with kotlin

  • 2. whoami ● Principal Developer @Wix ● Former Software Architect @Gett ● Author of “Hands-on Design Patterns with Kotlin” book ● StackOverflow junkie, top 2% this year ● Occasional Medium writer ● Currently living in London
  • 3. Intro ● “Design Patterns” by “Gang of Four” book was written back in ‘92. This is the only edition of the book. All examples in the book are either in C++ or SmallTalk ● Somebody once said that “design patterns are workarounds for shortcomings of particular language”. But he was fan of Lisp, so we can disregard that saying ● Disclaimer: all your favorite design patterns, including Singleton, will work in Kotlin as-is. Still, there are often better ways to achieve the same goal
  • 4. Kotlin ● Programming language from JetBrains, authors of IntelliJ IDE ● Runs on JVM (but can also be transpiled into JavaScript or platform native code) ● Still more concise than Java 12 ● Typesafe (hi, Groovy!) ● Null-safe ● Pragmatic (hi, Scala!)
  • 5. Singleton “Ensure a class has only one instance, and provide a global point of access to it.” public final class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } In Java: volatile synchronized instance static private static
  • 6. Singleton - continued object Singleton Taken directly from Scala CounterSingleton.INSTANCE.increment(); When called from Java, instead of usual .getInstance() uses INSTANCE field CounterSingleton.increment() Very concise usage syntax: In Kotlin:
  • 7. Builder “Allows constructing complex objects step by step” ElasticSearch API, for example, just LOVES builders... client.prepareSearch("documents") .setQuery(query(dressQuery)) .addSort(RANK_SORT) .addSort(SEARCHES_SORT) .get()
  • 8. Builder - continued In Kotlin, often can be replaced with combination of default parameters and .apply() function data class Mail(val to: String, var title: String = "", var message: String = "", var cc: List<String> = listOf(), var bcc: List<String> = listOf(), val attachments: List<java.io.File> = listOf()) { fun message(m: String) = apply { message = m } // No need to "return this" } val mail = Mail("bill.gates@microsoft.com") .message("How are you?").apply { cc = listOf("s.ballmer@microsoft.com") bcc = listOf("pichais@gmail.com") } Less boilerplate, same readability
  • 9. Proxy “Provides a substitute or placeholder for another object” Decorator and Proxy have different purposes but similar structures. Both describe how to provide a level of indirection to another object, and the implementations keep a reference to the object to which they forward requests. In Kotlin: by keyword is used for such delegation val image: File by lazy { println("Fetching image over network") val f = File.createTempFile("cat", ".jpg") URL(url).openStream().use { it.copyTo(BufferedOutputStream(f.outputStream())) }.also { println("Done fetching") } f }
  • 10. Iterator “Abstracts traversal of data structures in a linear way” class MyDataStructure<T> implements Iterable<T> { ... } In Java, this is built-in as Iterable interface Same will work also in Kotlin class MyDataStructure<T>: Iterable<T> { ... }
  • 11. Iterator - continued But in order not to have to implement too many interfaces (Android API, anyone?), you can use iterator() function instead: class MyDataStructure<T> { operator fun iterator() = object: Iterator<T> { override fun hasNext(): Boolean { ... } override fun next(): T { ... } } } Note the “operator” keyword before the name of the function.
  • 12. State “Allows an object to alter its behavior when its internal state changes” sealed class Mood object Still : Mood() // class Aggressive(val madnessLevel: Int) : Mood() object Retreating : Mood() object Dead : Mood() Kotlin sealed classes are great for state management Since all descendants of a sealed class must reside in the same file, you also avoid lots of small files describing states in your project
  • 13. State - continued Best feature is that compiler makes sure that you check all states when using sealed class override fun seeHero() { mood = when(mood) { is Still -> Aggressive(2) is Aggressive -> Retreating is Retreating -> Aggressive(1) // Doesn't compile, when must be exhaustive } } override fun seeHero() { mood = when(mood) { is Still -> Aggressive(2) is Aggressive -> Retreating is Retreating -> Aggressive(1) is Dead -> Dead // Better } } You must either specify all conditions, or use else block
  • 14. Strategy “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.” class OurHero { private var direction = Direction.LEFT private var x: Int = 42 private var y: Int = 173 // Strategy var currentWeapon = Weapons.peashooter val shoot = fun() { currentWeapon(x, y, direction) } } In Kotlin functions are first class citizens. If you want to replace a method - replace a method, don’t talk.
  • 15. Strategy - continued object Weapons { val peashooter = fun(x: Int, y: Int, direction: Direction) { // Fly straight } val banana = fun(x: Int, y: Int, direction: Direction) { // Return when you hit screen border } val pomegranate = fun(x: Int, y: Int, direction: Direction) { // Explode when you hit first enemy } } You can encapsulate all available strategies And replace them at will val h = OurHero() h.shoot() // peashooter h.currentWeapon = Weapons.banana h.shoot() // banana This is typesafe (hi, JavaScript!), and you don’t need to implement an interface
  • 16. Deferred value Not once I’ve heard JavaScript developers state that they don’t need design patterns in JavaScript. But Deferred value is one of the concurrent design patterns, and it’s widely used nowadays Also called Future or Promise with(GlobalScope) { val userProfile: Deferred<String> = async { delay(Random().nextInt(100).toLong()) "Profile" } } val profile: String = userProfile.await() In Kotlin provided as part of coroutines library:
  • 17. Fan Out “Deliver message to multiple destinations without halting the process” Producer Consumer 1 Consumer 2 Consumer 3 “r” “n” “d” Used to distribute work Each message delivered to only one consumer, semi-randomly Kotlin coroutine library provides ReceiveChannel for that purpose fun CoroutineScope.producer(): ReceiveChannel<String> = produce { for (i in 1..1_000_000) { for (c in 'a' .. 'z') { send(c.toString()) // produce next } } }
  • 18. Fan Out - continued Consumers can iterate over the channel, until it’s closed fun CoroutineScope.consumer(id: Int, channel: ReceiveChannel<String>) = launch { for (msg in channel) { println("Processor #$id received $msg") } } Here we distribute work between 4 consumers: val producer = producer() val processors = List(4) { consumer(it, producer) } for (p in processors) { p.join() }
  • 19. Fan In Similar to Fan Out pattern, Fan In relies on coroutines library and channels “Receive messages from multiple sources concurrently” fun CoroutineScope.collector(): SendChannel<Int> = actor { for (msg in channel) { println("Got $msg") } } Multiple producers are able to send to the same channel fun CoroutineScope.producer(id: Int, channel: SendChannel<Int>) = launch { repeat(10_000) { channel.send(id) } }
  • 20. Fan In - continued val collector = collector() val producers = List(4) { producer(it, collector) } producers.forEach { it.join() } Multiple producers are able to send to the same channel Outputs: ... Got 0 Got 0 Got 1 Got 2 Got 3 Got 0 Got 0 ...
  • 21. Summary ● Design patterns are everywhere ● Like any new language (unless it’s Go), Kotlin learns from shortcomings of its predecessors ● Kotlin has a lot of design patterns built in, as either idioms, language constructs or extension libraries ● Design patterns are not limited by GoF book
  • 23. Question time Thanks a lot for attending! Code: https://github.com/AlexeySoshin/KotlinFanInOutAnimation Keep in touch: ● https://twitter.com/alexey_soshin ● https://stackoverflow.com/users/5985853/alexey-soshin ● https://github.com/alexeysoshin

Hinweis der Redaktion

  1. © https://sourcemaking.com/design_patterns/singleton
  2. © https://sourcemaking.com/design_patterns/singleton
  3. © https://refactoring.guru/design-patterns/builder
  4. © https://refactoring.guru/design-patterns/builder
  5. © https://sourcemaking.com/design_patterns/proxy
  6. © https://en.wikipedia.org/wiki/Fan-out_(software) © https://kotlinlang.org/docs/reference/coroutines/channels.html#fan-out
  7. © https://en.wikipedia.org/wiki/Fan-out_(software) © https://kotlinlang.org/docs/reference/coroutines/channels.html#fan-out