SlideShare una empresa de Scribd logo
1 de 56
Descargar para leer sin conexión
Haim Yadid
Building Microservices with Kotlin
Disclaimer
• The purpose of this talk is to share our experience and
with Kotlin not to teach the language syntax. I will delve
into some details for for the basics just go to the
documentation (https://kotlinlang.org/docs/reference/)
• While comparison between Kotlin and Scala is tempting
this will not be the focus of the talk.
About Me
• Developing software since 1984 (Boy, am I getting old?)
• Basic -> Pascal -> C -> C++ -> Java -> Kotlin
• Developer , architect, group manager
• Independent performance expert for 8 years
• Head of backend engineering in
Drakaris
• Founded in the Beginning of 2016
• Disrupt the small businesses insurance field
• Providing online experience which is simple, fast and
transparent
• HQ@Palo Alto RnD@Kfar Saba (Israel)
• We started to write real code on May 2016
Lookingforalanguage
JVM Languages
Java Scala Clojure
Groovy/
JRuby
Java8
Strongly

Typed
Loosely

Typed
OO/verbose Functional/Rich
))))))))))))))))))))))))
Ceylon
JVM Languages
Java Scala
Groovy/
JRuby
Java8
Strongly

Typed
Loosely

Typed
OO/verbose Functional/Rich
Clojure))))))))))))))))))))))))
Ceylon
Kotlin
What is Kotlin ?
• Strongly typed programming language
• For the JVM, Android and the browser (JS)
• 100% interoperable with Java™ (well almost)
• Developed by JetBrains
• Revealed as an open source in July 2011
• v1.0 Release on Feb 2016
• 1.1.51 current stable version (as of 28-Sep-2017)
• 1.2 is in EA
Kotlin Design Goals
• Concise
• Safe
• Versatile
• Practical
• Interoperable
Bottom Line
HugeSuccess
Kotlin Adoption
• Android official language
• 9 talks in JavaOne 2017
• Community enthusiasm ( hype ?)
We use Kotlin for
• Building our backend micro-services over DropWizard
(deployed to AWS)
• Building serverless endpoints (AWS Lambda) 





8 micro
services
12 Lambda
functions
120K lines of
Kotlin code
5K lines of
Java code
Kotlin version upgrade
• Started at 1.0.2
• Upgraded to every release of Kotlin immediately
• Migration to 1.1.0 ( Java8 support ) was smooth
• No breaking changes so far (for us)
• Now on 1.1.51
Onboarding
• Onboarding of new Java developers proved to be
smooth
• Java developers are capable to developing in Kotlin on
the same pace they are able to understand the
architecture
Java Ecosystem
Java Ecosystem
• Java open source libraries works well with Kotlin.
• Just add the dependency to you build file and you are
done
Kotlin Primitives
• kotlin.Int => int
• kotlin.Double => double
• kotlin.String => java.lang.String
Collections
• kotlin.HashMap = java.util.LinkedHashMap
• Underlying Java collections
• Maps and lists can be either mutable and immutable
• “Immutability” = immutable view (Compromise)
Collections
val heros = mapOf("Terion" to "Lannister", "John" to "Snow")

heros["Terion"]
val chars2 = mutableMapOf<String,String>()

chars2["A girl"] = "has no name"
val sigils = [“Direwolf", "Lion", “Three headed Dragon",
“Flower"]

println(sigils[0])
heros[“Aria"] = “Stark"
Dropwizard AWS Lambda (Java)
Third Party Libraries
KotlinJDK8
log4jJersey
RDS (mysql)
JettyJackson
logback
Jackson
Jersey
client
PDF box Flyway
Dropwizard

Swagger
Stripe-
java
XMPBox guava
Jersey
client
JUnit
Mockito*JDBI
Dropwizard AWS Lambda (Java)
Third Party Libraries
KotlinJDK8
log4jJersey
RDS (mysql)
JettyJackson
logback
Jackson
Jersey
client
PDF box Flyway
Dropwizard

Swagger
Stripe-
java
XMPBox guava
Jersey
client
JUnit
MockitoJDBI
Mockito

Kotlin

*
Mockito Kotlin
• when -> `when` -> whenever
• Solve Null safety issues with any()
• DSL like syntax using Lambda expressions
Project organization
• Build with kotlin-maven plugin
• Same source paths as java
• src/main/java
• src/test/java
• Dependency management :
• kotlin-stdlib
• kotlin-reflect
• kotlin-stdlib-jre7
• kotlin-stdlib-jre8

Extension Functions
Extension functions
• Add functionality to a class w/o inheritance
• Only extend functionality cannot override members
• Not part of the class
• Static methods with the receiver as first a parameter
• (Not like ruby monkey patching )



fun String.paperWrap = “[$this]”
“hello”.paperWrap

-> “[hello]”
ResultSet null values
• When querying a java.sql.ResultSet for a value that is
nullable
• getLong will return 0 when the value is null and you are
expected to invoke wasNull afterwards
fun ResultSet.getNullableLong(colName: String): Long? {
val value = this.getLong(colName)
return if (this.wasNull()) null else value
}
Measuring endpoint duration
• Write endpoint duration to log entries
• ES/Kibana (we use logz.io)
• When we report our data to we have duration field for
every endpoint invocation.
Measuring endpoint duration
fun Logger.infoWithDuration(message: String,
vararg additionalArgs: Any){
loggerActionWithDuration {
if (additionalArgs.isNotEmpty())
info(message,*additionalArgs)
else
info(message)
}
}
loggerActionWithDuration
inline fun Logger.loggerActionWithDuration(action: () -> Unit){
updateDurationMDCValue()
action.invoke()
MDC.remove(MDC_DURATION_KEY)
}
Calculating endpoint duration
• store on MDC the transaction start time
• in this method we store the the duration from start on
MDC as well

fun Logger.updateDurationMDCValue() {
val startTimestampMDCValue = MDC.get(MDC_TRANSACTION_START_TS_KEY)
if(startTimestampMDCValue!=null){
val startTimestamp = startTimestampMDCValue.toLong()
val requestDuration = now() - startTimestamp
MDC.put(MDC_DURATION_KEY, requestDuration.toString())
}
}
Request Filter
class DurationStartFilter : ContainerRequestFilter {
override fun filter(requestContext: ContainerRequestContext) {
val transStartTS = now()
MDC.put(MDC_TRANSACTION_START_TS_KEY, transStartTS.toString())
}
}
Response Filter
class DurationFilter : ContainerResponseFilter {
val logger: Logger = LoggerFactory.getLogger(DurationFilter::class.java)
override fun filter(containerRequestContext: ContainerRequestContext?,
containerResponseContext: ContainerResponseContext?) {
logger.infoWithDuration("Request processing finished.")
}
}
Null Safety
Null Safety
• Nullability part of the type of an object
• Option[T] Optional<T>
• Swift anyone ?









var msg : String = "Welcome"

msg = null
val nullableMsg : String? = null
Safe operator ?.
• The safe call operator ?. will result null on null receiver
• Elvis operator for default











fun funny(funnier: String?): Int? {



println(x?.length ?: "")

return x?.length

}
Bang Bang !!
• The bang bang !! throws an NPE if object is null



fun funny(funnier: String?): String {

return funnier!!

}
Null Pollution
• It is really easy to pollute our code with nulls
• Java code is not handling nulls properly
• map.get() or the [] shortcut possibly return null
• map[“key”]!! with throw KotlinNullPointerException
Require
• Our own implementation
• Extension function
• Throws a clearer exception
fun <T> Map<String, T>.require(key: String, allowEmpty: Boolean = false): T {
val value = this[key] ?:
throw IllegalArgumentException("Required aMap["$key"] is missing. aMap.size = ${this.size}")
if (!allowEmpty) {
if (value is String) {
if (value.isEmpty()) {
throw IllegalArgumentException("Required aMap["$key"] is empty. aMap.size = ${this.size}")
}
}
}
return value
}
getValue
• Since Kotlin 1.1
• Throws a Descriptive NoSuchElementException which
includes key name
val value = mappy.getValue("key")
Delegate by map
data class Person(val firstName: String,
val lastName: String,
var props: MutableMap<String, String>) {
var businessname: String by props
val emailaddress: String by props
}
JSON Serialization
Microservices Talk
• Over HTTP
• JSON serialization













{ “firstName”: “Eddard”,
“lastName” : “Stark” }
Service

A
Service

Winterfell
setLordOfWinterfell
DTOs
• Getter and setters for all fields
• Implementation of
• Implemented hashcode() equals()
• copy()
• destructuring (component1 component2 …)





data class Lord(val firstName: String, val lastName: String)
val starkInWinterfellS1 = Lord(“Eddard”,”Stark”)
val starkInWinterfellS2to3 = starkInWinterfell.copy(firstName = “Robb”)
val (first,last) = starkInWinterfell
Evolution Season 1 Episode 9
• Adding a field should not be a breaking change
• Ability to deserialize
• With missing field
• With additional field 







Service

A
Service

B
{
“firstName”: “Eddard”,
“lastName” : “Stark”,
“beheaded” : true
}
lordOfWinterfell
jackson-module-kotlin
• Introduces an introspection which do not need
annotations for most cases
• Nullable represents optional

data class Lord(
val firstName: String,
val lastName: String,
val beheaded: Boolean?,
)
ObjectMapper()
.registerModule(KotlinModule())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,true)
Delegate by map
data class Person(val firstName: String,
val lastName: String,
var props: MutableMap<String, String>) {
@get:JsonIgnore
val businessname: String by props
@get:JsonIgnore
val emailaddress: String by props
}
println(person.businessname)
Inline / Reified
execution_statuses Table
id name
1 success
2 referral
3 technical_error
4 decline
6 renewal
Enum
enum class ExecutionStatuses(
override val id: Int,
override val dbName: String) : DBEnum {
SUCCESS(1, "success"),
REFERRAL(2, "referral"),
TECHNICAL_ERROR(3, "technical_error"),
DECLINE(4, "decline"),
RENEWAL(5, "renewal");
}
DBEnum
interface DBEnum {
val id: Int
val dbName: String
companion object {
inline fun <reified T> fromId(id: Int): T where T : Enum<T>, T : DBEnum {
return enumValues<T>().first { it.id == id }
}
inline fun <reified T> fromName(name: String): T where T : Enum<T>, T :
DBEnum {
return enumValues<T>().first { it.dbName == name }
}
}
}
Integration Test
inline fun <reified T> verifyValuesAreConsistent(dbIdToName:
MutableMap<Int, String>) where T : Enum<T>, T : DBEnum {
val enumValues = enumValues<T>()
expect(dbIdToName.size).toBe(enumValues.size)
dbIdToName.forEach {
val dbId = it.key
val dbName = it.value
expect(DBEnum.fromId<T>(dbId).dbName).toBe(dbName)
expect(DBEnum.fromName<T>(dbName).id).toBe(dbId)
}
}
Integration Test DSL
TestStage
abstract class TestStage<out T> {
lateinit var testIT: UnderwritingCycleTest
lateinit var testDataSet: TestDataSet
abstract fun construct(testIT: UnderwritingCycleTest,
testDataSet: TestDataSet): T
}
Test
@Ignore
@Test
fun e2eFlowWithCarrierTennesseeState() {
val testDataSet = TestDataSet.build(this, PartnerTestData) {
overrideParam("state", "TN")
}
startFlow(testDataSet)
.sendBusinessDetails()
.screenRequest()
.createQuoteSync()
.preSelect()
.select()
.paySuccessWithoutBind()
.bindFailure{
assertEquals(CarrierBindStatuses.MANUAL_STEPS_REQUIRED.dbName,
this.carrierBindStatus)
}
}
Lorem Ipsum Dolor
Questions?

Más contenido relacionado

La actualidad más candente

2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than everKai Koenig
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designAndrey Breslav
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan s.r.o.
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.Ruslan Shevchenko
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation MobileAcademy
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Arnaud Giuliani
 

La actualidad más candente (20)

Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
2017: Kotlin - now more than ever
2017: Kotlin - now more than ever2017: Kotlin - now more than ever
2017: Kotlin - now more than ever
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Kotlin
KotlinKotlin
Kotlin
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 

Similar a Building microservices with Kotlin

The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at TwitterAlex Payne
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...Julia Cherniak
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorTrayan Iliev
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)Eugene Yokota
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Exploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesExploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesTobias Lindaaker
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormDavorin Vukelic
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
JVM languages "flame wars"
JVM languages "flame wars"JVM languages "flame wars"
JVM languages "flame wars"Gal Marder
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift AwesomeSokna Ly
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Sunghyouk Bae
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Building DSLs with Scala
Building DSLs with ScalaBuilding DSLs with Scala
Building DSLs with ScalaMohit Jaggi
 

Similar a Building microservices with Kotlin (20)

The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
 
C# - What's next
C# - What's nextC# - What's next
C# - What's next
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Exploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic LanguagesExploiting Concurrency with Dynamic Languages
Exploiting Concurrency with Dynamic Languages
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
JVM languages "flame wars"
JVM languages "flame wars"JVM languages "flame wars"
JVM languages "flame wars"
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Building DSLs with Scala
Building DSLs with ScalaBuilding DSLs with Scala
Building DSLs with Scala
 

Más de Haim Yadid

Loom me up Scotty! Project Loom - What's in it for Me?
Loom me up Scotty!  Project Loom - What's in it for Me?Loom me up Scotty!  Project Loom - What's in it for Me?
Loom me up Scotty! Project Loom - What's in it for Me?Haim Yadid
 
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
“Show Me the Garbage!”, Garbage Collection a Friend or a FoeHaim Yadid
 
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the UglyKotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the UglyHaim Yadid
 
“Show Me the Garbage!”, Understanding Garbage Collection
“Show Me the Garbage!”, Understanding Garbage Collection“Show Me the Garbage!”, Understanding Garbage Collection
“Show Me the Garbage!”, Understanding Garbage CollectionHaim Yadid
 
Java Memory Structure
Java Memory Structure Java Memory Structure
Java Memory Structure Haim Yadid
 
Basic JVM Troubleshooting With Jmx
Basic JVM Troubleshooting With JmxBasic JVM Troubleshooting With Jmx
Basic JVM Troubleshooting With JmxHaim Yadid
 
The Freelancer Journey
The Freelancer JourneyThe Freelancer Journey
The Freelancer JourneyHaim Yadid
 
Let's talk about Garbage Collection
Let's talk about Garbage CollectionLet's talk about Garbage Collection
Let's talk about Garbage CollectionHaim Yadid
 
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...Haim Yadid
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingHaim Yadid
 
Java 8 Launch - MetaSpaces
Java 8 Launch - MetaSpacesJava 8 Launch - MetaSpaces
Java 8 Launch - MetaSpacesHaim Yadid
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
A short Intro. to Java Mission Control
A short Intro. to Java Mission ControlA short Intro. to Java Mission Control
A short Intro. to Java Mission ControlHaim Yadid
 
Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Haim Yadid
 
Tales About Scala Performance
Tales About Scala PerformanceTales About Scala Performance
Tales About Scala PerformanceHaim Yadid
 
Israeli JUG - IL JUG presentation
Israeli JUG -  IL JUG presentation Israeli JUG -  IL JUG presentation
Israeli JUG - IL JUG presentation Haim Yadid
 

Más de Haim Yadid (18)

Loom me up Scotty! Project Loom - What's in it for Me?
Loom me up Scotty!  Project Loom - What's in it for Me?Loom me up Scotty!  Project Loom - What's in it for Me?
Loom me up Scotty! Project Loom - What's in it for Me?
 
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
 
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the UglyKotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
 
“Show Me the Garbage!”, Understanding Garbage Collection
“Show Me the Garbage!”, Understanding Garbage Collection“Show Me the Garbage!”, Understanding Garbage Collection
“Show Me the Garbage!”, Understanding Garbage Collection
 
Java Memory Structure
Java Memory Structure Java Memory Structure
Java Memory Structure
 
Basic JVM Troubleshooting With Jmx
Basic JVM Troubleshooting With JmxBasic JVM Troubleshooting With Jmx
Basic JVM Troubleshooting With Jmx
 
The Freelancer Journey
The Freelancer JourneyThe Freelancer Journey
The Freelancer Journey
 
Let's talk about Garbage Collection
Let's talk about Garbage CollectionLet's talk about Garbage Collection
Let's talk about Garbage Collection
 
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profiling
 
Java 8 Launch - MetaSpaces
Java 8 Launch - MetaSpacesJava 8 Launch - MetaSpaces
Java 8 Launch - MetaSpaces
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
A short Intro. to Java Mission Control
A short Intro. to Java Mission ControlA short Intro. to Java Mission Control
A short Intro. to Java Mission Control
 
Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions Java Enterprise Edition Concurrency Misconceptions
Java Enterprise Edition Concurrency Misconceptions
 
Tales About Scala Performance
Tales About Scala PerformanceTales About Scala Performance
Tales About Scala Performance
 
Israeli JUG - IL JUG presentation
Israeli JUG -  IL JUG presentation Israeli JUG -  IL JUG presentation
Israeli JUG - IL JUG presentation
 

Último

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Último (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

Building microservices with Kotlin

  • 2. Disclaimer • The purpose of this talk is to share our experience and with Kotlin not to teach the language syntax. I will delve into some details for for the basics just go to the documentation (https://kotlinlang.org/docs/reference/) • While comparison between Kotlin and Scala is tempting this will not be the focus of the talk.
  • 3. About Me • Developing software since 1984 (Boy, am I getting old?) • Basic -> Pascal -> C -> C++ -> Java -> Kotlin • Developer , architect, group manager • Independent performance expert for 8 years • Head of backend engineering in Drakaris
  • 4. • Founded in the Beginning of 2016 • Disrupt the small businesses insurance field • Providing online experience which is simple, fast and transparent • HQ@Palo Alto RnD@Kfar Saba (Israel) • We started to write real code on May 2016
  • 6. JVM Languages Java Scala Clojure Groovy/ JRuby Java8 Strongly
 Typed Loosely
 Typed OO/verbose Functional/Rich )))))))))))))))))))))))) Ceylon
  • 7. JVM Languages Java Scala Groovy/ JRuby Java8 Strongly
 Typed Loosely
 Typed OO/verbose Functional/Rich Clojure)))))))))))))))))))))))) Ceylon Kotlin
  • 8. What is Kotlin ? • Strongly typed programming language • For the JVM, Android and the browser (JS) • 100% interoperable with Java™ (well almost) • Developed by JetBrains • Revealed as an open source in July 2011 • v1.0 Release on Feb 2016 • 1.1.51 current stable version (as of 28-Sep-2017) • 1.2 is in EA
  • 9. Kotlin Design Goals • Concise • Safe • Versatile • Practical • Interoperable
  • 12. Kotlin Adoption • Android official language • 9 talks in JavaOne 2017 • Community enthusiasm ( hype ?)
  • 13. We use Kotlin for • Building our backend micro-services over DropWizard (deployed to AWS) • Building serverless endpoints (AWS Lambda) 
 
 
 8 micro services 12 Lambda functions 120K lines of Kotlin code 5K lines of Java code
  • 14. Kotlin version upgrade • Started at 1.0.2 • Upgraded to every release of Kotlin immediately • Migration to 1.1.0 ( Java8 support ) was smooth • No breaking changes so far (for us) • Now on 1.1.51
  • 15. Onboarding • Onboarding of new Java developers proved to be smooth • Java developers are capable to developing in Kotlin on the same pace they are able to understand the architecture
  • 17. Java Ecosystem • Java open source libraries works well with Kotlin. • Just add the dependency to you build file and you are done
  • 18. Kotlin Primitives • kotlin.Int => int • kotlin.Double => double • kotlin.String => java.lang.String
  • 19. Collections • kotlin.HashMap = java.util.LinkedHashMap • Underlying Java collections • Maps and lists can be either mutable and immutable • “Immutability” = immutable view (Compromise)
  • 20. Collections val heros = mapOf("Terion" to "Lannister", "John" to "Snow")
 heros["Terion"] val chars2 = mutableMapOf<String,String>()
 chars2["A girl"] = "has no name" val sigils = [“Direwolf", "Lion", “Three headed Dragon", “Flower"]
 println(sigils[0]) heros[“Aria"] = “Stark"
  • 21. Dropwizard AWS Lambda (Java) Third Party Libraries KotlinJDK8 log4jJersey RDS (mysql) JettyJackson logback Jackson Jersey client PDF box Flyway Dropwizard
 Swagger Stripe- java XMPBox guava Jersey client JUnit Mockito*JDBI
  • 22. Dropwizard AWS Lambda (Java) Third Party Libraries KotlinJDK8 log4jJersey RDS (mysql) JettyJackson logback Jackson Jersey client PDF box Flyway Dropwizard
 Swagger Stripe- java XMPBox guava Jersey client JUnit MockitoJDBI Mockito
 Kotlin
 *
  • 23. Mockito Kotlin • when -> `when` -> whenever • Solve Null safety issues with any() • DSL like syntax using Lambda expressions
  • 24. Project organization • Build with kotlin-maven plugin • Same source paths as java • src/main/java • src/test/java • Dependency management : • kotlin-stdlib • kotlin-reflect • kotlin-stdlib-jre7 • kotlin-stdlib-jre8

  • 26. Extension functions • Add functionality to a class w/o inheritance • Only extend functionality cannot override members • Not part of the class • Static methods with the receiver as first a parameter • (Not like ruby monkey patching )
 
 fun String.paperWrap = “[$this]” “hello”.paperWrap
 -> “[hello]”
  • 27. ResultSet null values • When querying a java.sql.ResultSet for a value that is nullable • getLong will return 0 when the value is null and you are expected to invoke wasNull afterwards fun ResultSet.getNullableLong(colName: String): Long? { val value = this.getLong(colName) return if (this.wasNull()) null else value }
  • 28. Measuring endpoint duration • Write endpoint duration to log entries • ES/Kibana (we use logz.io) • When we report our data to we have duration field for every endpoint invocation.
  • 29. Measuring endpoint duration fun Logger.infoWithDuration(message: String, vararg additionalArgs: Any){ loggerActionWithDuration { if (additionalArgs.isNotEmpty()) info(message,*additionalArgs) else info(message) } }
  • 30. loggerActionWithDuration inline fun Logger.loggerActionWithDuration(action: () -> Unit){ updateDurationMDCValue() action.invoke() MDC.remove(MDC_DURATION_KEY) }
  • 31. Calculating endpoint duration • store on MDC the transaction start time • in this method we store the the duration from start on MDC as well
 fun Logger.updateDurationMDCValue() { val startTimestampMDCValue = MDC.get(MDC_TRANSACTION_START_TS_KEY) if(startTimestampMDCValue!=null){ val startTimestamp = startTimestampMDCValue.toLong() val requestDuration = now() - startTimestamp MDC.put(MDC_DURATION_KEY, requestDuration.toString()) } }
  • 32. Request Filter class DurationStartFilter : ContainerRequestFilter { override fun filter(requestContext: ContainerRequestContext) { val transStartTS = now() MDC.put(MDC_TRANSACTION_START_TS_KEY, transStartTS.toString()) } }
  • 33. Response Filter class DurationFilter : ContainerResponseFilter { val logger: Logger = LoggerFactory.getLogger(DurationFilter::class.java) override fun filter(containerRequestContext: ContainerRequestContext?, containerResponseContext: ContainerResponseContext?) { logger.infoWithDuration("Request processing finished.") } }
  • 35. Null Safety • Nullability part of the type of an object • Option[T] Optional<T> • Swift anyone ?
 
 
 
 
 var msg : String = "Welcome"
 msg = null val nullableMsg : String? = null
  • 36. Safe operator ?. • The safe call operator ?. will result null on null receiver • Elvis operator for default
 
 
 
 
 
 fun funny(funnier: String?): Int? {
 
 println(x?.length ?: "")
 return x?.length
 }
  • 37. Bang Bang !! • The bang bang !! throws an NPE if object is null
 
 fun funny(funnier: String?): String {
 return funnier!!
 }
  • 38. Null Pollution • It is really easy to pollute our code with nulls • Java code is not handling nulls properly • map.get() or the [] shortcut possibly return null • map[“key”]!! with throw KotlinNullPointerException
  • 39. Require • Our own implementation • Extension function • Throws a clearer exception fun <T> Map<String, T>.require(key: String, allowEmpty: Boolean = false): T { val value = this[key] ?: throw IllegalArgumentException("Required aMap["$key"] is missing. aMap.size = ${this.size}") if (!allowEmpty) { if (value is String) { if (value.isEmpty()) { throw IllegalArgumentException("Required aMap["$key"] is empty. aMap.size = ${this.size}") } } } return value }
  • 40. getValue • Since Kotlin 1.1 • Throws a Descriptive NoSuchElementException which includes key name val value = mappy.getValue("key")
  • 41. Delegate by map data class Person(val firstName: String, val lastName: String, var props: MutableMap<String, String>) { var businessname: String by props val emailaddress: String by props }
  • 43. Microservices Talk • Over HTTP • JSON serialization
 
 
 
 
 
 
 { “firstName”: “Eddard”, “lastName” : “Stark” } Service
 A Service
 Winterfell setLordOfWinterfell
  • 44. DTOs • Getter and setters for all fields • Implementation of • Implemented hashcode() equals() • copy() • destructuring (component1 component2 …)
 
 
 data class Lord(val firstName: String, val lastName: String) val starkInWinterfellS1 = Lord(“Eddard”,”Stark”) val starkInWinterfellS2to3 = starkInWinterfell.copy(firstName = “Robb”) val (first,last) = starkInWinterfell
  • 45. Evolution Season 1 Episode 9 • Adding a field should not be a breaking change • Ability to deserialize • With missing field • With additional field 
 
 
 
 Service
 A Service
 B { “firstName”: “Eddard”, “lastName” : “Stark”, “beheaded” : true } lordOfWinterfell
  • 46. jackson-module-kotlin • Introduces an introspection which do not need annotations for most cases • Nullable represents optional
 data class Lord( val firstName: String, val lastName: String, val beheaded: Boolean?, ) ObjectMapper() .registerModule(KotlinModule()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,true)
  • 47. Delegate by map data class Person(val firstName: String, val lastName: String, var props: MutableMap<String, String>) { @get:JsonIgnore val businessname: String by props @get:JsonIgnore val emailaddress: String by props } println(person.businessname)
  • 49. execution_statuses Table id name 1 success 2 referral 3 technical_error 4 decline 6 renewal
  • 50. Enum enum class ExecutionStatuses( override val id: Int, override val dbName: String) : DBEnum { SUCCESS(1, "success"), REFERRAL(2, "referral"), TECHNICAL_ERROR(3, "technical_error"), DECLINE(4, "decline"), RENEWAL(5, "renewal"); }
  • 51. DBEnum interface DBEnum { val id: Int val dbName: String companion object { inline fun <reified T> fromId(id: Int): T where T : Enum<T>, T : DBEnum { return enumValues<T>().first { it.id == id } } inline fun <reified T> fromName(name: String): T where T : Enum<T>, T : DBEnum { return enumValues<T>().first { it.dbName == name } } } }
  • 52. Integration Test inline fun <reified T> verifyValuesAreConsistent(dbIdToName: MutableMap<Int, String>) where T : Enum<T>, T : DBEnum { val enumValues = enumValues<T>() expect(dbIdToName.size).toBe(enumValues.size) dbIdToName.forEach { val dbId = it.key val dbName = it.value expect(DBEnum.fromId<T>(dbId).dbName).toBe(dbName) expect(DBEnum.fromName<T>(dbName).id).toBe(dbId) } }
  • 54. TestStage abstract class TestStage<out T> { lateinit var testIT: UnderwritingCycleTest lateinit var testDataSet: TestDataSet abstract fun construct(testIT: UnderwritingCycleTest, testDataSet: TestDataSet): T }
  • 55. Test @Ignore @Test fun e2eFlowWithCarrierTennesseeState() { val testDataSet = TestDataSet.build(this, PartnerTestData) { overrideParam("state", "TN") } startFlow(testDataSet) .sendBusinessDetails() .screenRequest() .createQuoteSync() .preSelect() .select() .paySuccessWithoutBind() .bindFailure{ assertEquals(CarrierBindStatuses.MANUAL_STEPS_REQUIRED.dbName, this.carrierBindStatus) } }