SlideShare une entreprise Scribd logo
1  sur  64
Télécharger pour lire hors ligne
Poniendo
by @andres_viedma
en producción
A palos
MAD · NOV 24-25 · 2017
Andrés ViedmaAndrés Viedma
@andres_viedma@andres_viedma
01 KOTLIN
Null safety
fun printStringLength(maybeString: String?) {
// maybeString.length would not compile
if (maybeString != null) {
// maybeString cannot be null now, it's a String
println(maybeString.length)
} else {
println("<empty>")
}
}
”My billion dollars mistake”
Tony Hoare
fun printStringLength1(maybeString: String?) {
maybeString?.let { s -> println(s) }
}
fun printStringLengthOrEmpty(maybeString: String?) {
println(maybeString?.length ?: "<empty>")
}
Null safety
A small immutable Kotlin class
data class TokenInfo(
val tokenType: String = “auth”,
val identity: String
val expiration: Int? = null
)
Constructor with Properties
class TokenInfo(
val tokenType: String,
val identity: String
(…)
)
public final class TokenInfo {
private final String tokenType;
private final String identity;
(…)
public TokenInfo(
String tokenType,
String identity,
(…)) {
this.tokenType = tokenType;
this.identity = identity;
(…)
}
public final String getTokenType() {
return tokenType;
}
public final String getIdentity() {
return identity;
}
}
Getters and Setters
class TokenInfo(
val tokenType: String,
val identity: String
(…)
)
public final class TokenInfo {
private final String tokenType;
private final String identity;
(…)
public TokenInfo(
String tokenType,
String identity,
(…)) {
this.tokenType = tokenType;
this.identity = identity;
(…)
}
public final String getTokenType() {
return tokenType;
}
public final String getIdentity() {
return identity;
}
}
Named arguments and optional values
class TokenInfo(
val tokenType: String = "auth",
val identity: String,
val expiration: Int? = null
)
val token = TokenInfo(identity = "xxx")
Immutable classes with
optional fields?
Constructors with lots of
parameters
Builder object
Data classes
data class TokenInfo(
val tokenType: String,
val identity: String
(…)
)
public final class TokenInfo {
(…)
public String toString() { (…) }
public int hashCode() { (…) }
public boolean equals(Object var1) { (…) }
public final TokenInfoId copy(String tokenType,
String identity) {
(…)
}
public final String component1() { (…) }
public final String component2() { (…) }
}
Immutability
made easier
Collections improvements
List<Person> persons = Arrays.asList(
new Person("Sansa", "Stark"),
new Person("Jon", "Snow"));
List<String> personNames = persons.stream()
.map(p -> p.getName() + " " + p.getSurname())
.collect(Collectors.toList());
val persons = listOf(
Person("Sansa", "Stark"),
Person("Jon", "Snow"))
val personNames = persons
.map { p -> "${p.name} ${p.surname}" }
Extension functions
Collections improvements
List<Integer> result = list.stream()
.flatMap(o -> o.isPresent() ?
Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
val result = list.filter { it != null }
List<Integer> result = list.stream()
.flatMap(o → o.map(Stream::of)
.orElseGet(Stream::empty))
.collect(Collectors.toList());
List<Integer> result = list.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
String Interpolation
List<Person> persons = Arrays.asList(
new Person("Sansa", "Stark"),
new Person("Jon", "Snow"));
List<String> personNames = persons.stream()
.map(p -> p.getName() + " " + p.getSurname())
.collect(Collectors.toList());
val persons = listOf(
Person("Sansa", "Stark"),
Person("Jon", "Snow"))
val personNames = persons
.map { p -> "${p.name} ${p.surname}" }
Type Inference
val persons = listOf(
Person("Sansa", "Stark"),
Person("Jon", "Snow"))
val personNames = persons
.map { p -> "${p.name} ${p.surname}" }
List<Person> persons = Arrays.asList(
new Person("Sansa", "Stark"),
new Person("Jon", "Snow"));
List<String> personNames = persons.stream()
.map(p -> p.getName() + " " + p.getSurname())
.collect(Collectors.toList());
Gotcha! Now the idea is trapped inside your head
Gotcha! Now the idea is trapped inside your head
Gotcha! Now the idea is trapped inside your head
02 LET'S DO IT!
Tell the team!
The conformist
Tell the team!
The conformist The idealist
Tell the team!
The conformist The idealist The responsible
Tell the team!
The conformist The idealist The responsible
AGGG ROOO RAGGAGGG ROOO RAGG
ROOOOOOOGHH!ROOOOOOOGHH!
What about the rest of the company?
Option 1...
Option 2: Talk to them
●
Can affect development time
●
Misunderstandings can increase bug rate
●
Service responsibility is not fixed
Not just YOUR team
Learning cost
●
Learning curve very smooth
●
On doubt, use Java style and methods
●
Not a real paradigm change
●
Same libraries and concepts
Learning cost ® BUT...
●
Good documentation
●
Short library
●
Is there a general interest in Kotlin in the company?
Kotlin community
Android devs pushing for a change
Learning cost ® BUT... (2)
●
It's production!
●
New technology, may have bugs
●
Adds code “behind the courtains”
●
Any weird behaviour affecting memory, garbage collection...
Can affect Performance
●
Same Java VM
●
You can see compiled bytecode
●
Decompile problematic code to Java and tune it
●
Start a component in Java and then convert it to Kotlin
Can affect Performance ® BUT...
●
Extension functions are just a trick, no overhead
●
Null checks are a small runtime overhead
●
Platform and base libraries are the sane
●
Kotlin library overhead not important for backend
Can affect Performance ® BUT... (2)
●
Increased build time
●
Find equivalent tools
●
Adaptation to those tools
Tooling problems
●
Same IDE: IntelliJ, Eclipse...
●
Same build tools: Maven, Gradle...
●
In a microservices architecture build time not so critical
Seconds?
Tooling problems ® BUT...
●
What if Kotlin stops being “cool”?
●
What if nobody uses it anymore?
●
What if it just dissapears?
Supported / created by Jetbrains
Long-term vision
Long-term vision ® BUT...
03 10 MONTHS
LATER...
●
Development time basically the same
●
Code Reviews more interesting!
●
Our Java platform was 100% compatible
Learning cost?
●
Rest of the company?
4 teams doing services in Kotlin
Kotlin now official in the company for Android
Learning cost?
final vs. open
Some Java libraries rely on
dinamically creating subclasses
●
Interceptors and other injection “black magic”
Spring, Guice…
●
Mocks: Mockito, Spock
Compiler plugins
●
All-open: Make classes open
Shortcut: Spring
●
No-args: Create a no-args constructor
Shortcut: JPA
Beware!: only by annotations
Compiler plugins ® All-open not enough
●
@Transactional problem (if no class annotation)
Explicit open class and methods
●
Mocks?
Mockito 2.1.0 “inline mocks”: “incubating”
Kotlin-runner library: explicit packages
Compiler plugins ® No-args not enough
●
Object Mapper libraries
Explicit no-args constructor
●
Spock tests
Named parameters don’t work from Java / Groovy
const val ONE = 1 // MyObject(1) NO OBJECTS ALLOWED
// Translated to: public static final
class Constants {
companion object {
const val TWO = 2 // MyObject(2) NO OBJECTS ALLOWED
// Translated to: inlined
val THREE = MyObject(3) // Translated to private static
// + Companion class with getter
@JvmField val FOUR = MyObject(4) // Translated to public static final
}
}
Constants: too many options?
https://blog.egorand.me/where-do-i-put-my-constants-in-kotlin/
val description: String (type after identifier)
val description: String (type after identifier)
Can affect Performance?
●
Eclipse with Kotlin and Groovy tests just don’t work
●
Eclipse incremental compilation a bit slow
●
Some crashes when updating IntelliJ plugin
●
Incremental build disabled by default in some versions
Maven+Gradle
●
Checkstyle, Findbugs…
Tooling problems?
●
Eclipse with Kotlin and Groovy tests just don’t work
●
Eclipse incremental compilation a bit slow
●
Some crashes when updating IntelliJ plugin
●
Incremental build disabled by default in some versions
Maven+Gradle
●
Checkstyle, Findbugs…
Tooling problems?
04 Beyond
the basics
Functional features
fun processPersonName(person: Person?, processor: (String) -> Boolean) =
processor(
when(person) {
null -> "null"
is AnonymousPerson -> "anonymous"
else -> when {
person.isBoss -> "a boss"
else -> "the simple ${person.name}"
}
}
)
●
Not 100% functional
●
Higher kind types
●
Typeclasses
●
Proposal (KEEP) in discussion to add them, by @raulraja
●
Kategory library - http://kategory.io/
Functional paradigm?
Black magic
companion { [constants: USER_ID, PRODUCTS, OK_RESULT...) }
val storeCatalogStub = Stub<StoreCatalog> {
getProductsForUserId(USER_ID) <= PRODUCTS
}
val storeMock = Mock<ProductStore>()
val purchaseHistoryMock: PurchaseHistory = Mock()
fun `Purchase correct product available in the store`() {
given("A valid user") {
userService.isValidUser(USER_ID) <= true
} `when`("The user tries to do the purchase") {
purchaseOperation.perform(USER_ID, PRODUCT_ID)
} then("Product is purchased") {
1 * storeMock.purchaseProduct(USER_ID, PRODUCT_ID, null.not()) <= OK_RESULT
} and("Operation is logged") {
(1..any) * purchaseHistoryMock.logProductPurchased(USER_ID, PRODUCT_ID, any())
} and("No more interactions") {
0 * any
}
}
Black magic
companion { [constants: USER_ID, PRODUCTS, OK_RESULT...) }
val storeCatalogStub = Stub<StoreCatalog> {
getProductsForUserId(USER_ID) <= PRODUCTS
}
val storeMock = Mock<ProductStore>()
val purchaseHistoryMock: PurchaseHistory = Mock()
fun `Purchase correct product available in the store`() {
given("A valid user") {
userService.isValidUser(USER_ID) <= true
} `when`("The user tries to do the purchase") {
purchaseOperation.perform(USER_ID, PRODUCT_ID)
} then("Product is purchased") {
1 * storeMock.purchaseProduct(USER_ID, PRODUCT_ID, null.not()) <= OK_RESULT
} and("Operation is logged") {
(1..any) * purchaseHistoryMock.logProductPurchased(USER_ID, PRODUCT_ID, any())
} and("No more interactions") {
0 * any
}
}
Lambda param after
parenthesis
Code generation
(compiler plugin)
Black magic
companion { [constants: USER_ID, PRODUCTS, OK_RESULT...) }
val storeCatalogStub = Stub<StoreCatalog> {
getProductsForUserId(USER_ID) <= PRODUCTS
}
val storeMock = Mock<ProductStore>()
val purchaseHistoryMock: PurchaseHistory = Mock()
fun `Purchase correct product available in the store`() {
given("A valid user") {
userService.isValidUser(USER_ID) <= true
} `when`("The user tries to do the purchase") {
purchaseOperation.perform(USER_ID, PRODUCT_ID)
} then("Product is purchased") {
1 * storeMock.purchaseProduct(USER_ID, PRODUCT_ID, null.not()) <= OK_RESULT
} and("Operation is logged") {
(1..any) * purchaseHistoryMock.logProductPurchased(USER_ID, PRODUCT_ID, any())
} and("No more interactions") {
0 * any
}
}
Operator overloading
Reified generics
Extension functions
https://github.com/Koxalen
More...
●
Coroutines
●
Type aliases
●
Sealed classes
●
Delegated properties
●
Inline functions
Android
●
Anko library
●
Consider performance and limits
7k methods (65k methods limit): 10%
380 KB
Compilation slower
Multi-platform
●
Javascript
Kotlin wrapper for ReactJS
●
Native
Kotlin plugin for CLion
Kotlin/Native iOS support
Not only the JVM!
KotlinConf app fully made with Kotlin
SO WHAT???05
Yay or Nay?
●
Controlled risk, but… worth it?
●
What’s the benefit?
Mostly syntatic sugar
Productivity really improved???
Yay or Nay?
●
Controlled risk, but… worth it?
●
What’s the benefit?
Mostly syntatic sugar
Productivity really improved???
How about thinking about PEOPLE
instead of PRODUCTS?
It’s all about LEARNING
and MOTIVATION
Questions?
Andrés Viedma · @andres_viedma

Contenu connexe

Tendances

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
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 hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Arnaud Giuliani
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
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
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designAndrey Breslav
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
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
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsMohammad Shaker
 
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
 

Tendances (19)

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
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 hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Kotlin
KotlinKotlin
Kotlin
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
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
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
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
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
 
Return of c++
Return of c++Return of c++
Return of c++
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
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
 

Similaire à Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsJigar Gosar
 
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
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
Type Driven Development @ Confitura 2014
Type Driven Development @ Confitura 2014Type Driven Development @ Confitura 2014
Type Driven Development @ Confitura 2014Maciek Próchniak
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in KotlinLuca Guadagnini
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android UpdateGarth Gilmour
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsTMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsIosif Itkin
 
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
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdfAndrey Breslav
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 

Similaire à Poniendo Kotlin en producción a palos (Kotlin in production, the hard way) (20)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Why Kotlin is your next language?
Why Kotlin is your next language? Why Kotlin is your next language?
Why Kotlin is your next language?
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 
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
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
Type Driven Development @ Confitura 2014
Type Driven Development @ Confitura 2014Type Driven Development @ Confitura 2014
Type Driven Development @ Confitura 2014
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Kotlin
KotlinKotlin
Kotlin
 
Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
 
Kotlin / Android Update
Kotlin / Android UpdateKotlin / Android Update
Kotlin / Android Update
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsTMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
 
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
 
C# Today and Tomorrow
C# Today and TomorrowC# Today and Tomorrow
C# Today and Tomorrow
 
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 

Dernier

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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
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
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
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
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
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
 
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
 
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
 
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
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
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
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 

Dernier (20)

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
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
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 - ...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
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
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
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
 
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...
 
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
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
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...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 

Poniendo Kotlin en producción a palos (Kotlin in production, the hard way)

  • 4.
  • 5. Null safety fun printStringLength(maybeString: String?) { // maybeString.length would not compile if (maybeString != null) { // maybeString cannot be null now, it's a String println(maybeString.length) } else { println("<empty>") } } ”My billion dollars mistake” Tony Hoare
  • 6. fun printStringLength1(maybeString: String?) { maybeString?.let { s -> println(s) } } fun printStringLengthOrEmpty(maybeString: String?) { println(maybeString?.length ?: "<empty>") } Null safety
  • 7. A small immutable Kotlin class data class TokenInfo( val tokenType: String = “auth”, val identity: String val expiration: Int? = null )
  • 8. Constructor with Properties class TokenInfo( val tokenType: String, val identity: String (…) ) public final class TokenInfo { private final String tokenType; private final String identity; (…) public TokenInfo( String tokenType, String identity, (…)) { this.tokenType = tokenType; this.identity = identity; (…) } public final String getTokenType() { return tokenType; } public final String getIdentity() { return identity; } }
  • 9. Getters and Setters class TokenInfo( val tokenType: String, val identity: String (…) ) public final class TokenInfo { private final String tokenType; private final String identity; (…) public TokenInfo( String tokenType, String identity, (…)) { this.tokenType = tokenType; this.identity = identity; (…) } public final String getTokenType() { return tokenType; } public final String getIdentity() { return identity; } }
  • 10. Named arguments and optional values class TokenInfo( val tokenType: String = "auth", val identity: String, val expiration: Int? = null ) val token = TokenInfo(identity = "xxx") Immutable classes with optional fields? Constructors with lots of parameters Builder object
  • 11. Data classes data class TokenInfo( val tokenType: String, val identity: String (…) ) public final class TokenInfo { (…) public String toString() { (…) } public int hashCode() { (…) } public boolean equals(Object var1) { (…) } public final TokenInfoId copy(String tokenType, String identity) { (…) } public final String component1() { (…) } public final String component2() { (…) } } Immutability made easier
  • 12. Collections improvements List<Person> persons = Arrays.asList( new Person("Sansa", "Stark"), new Person("Jon", "Snow")); List<String> personNames = persons.stream() .map(p -> p.getName() + " " + p.getSurname()) .collect(Collectors.toList()); val persons = listOf( Person("Sansa", "Stark"), Person("Jon", "Snow")) val personNames = persons .map { p -> "${p.name} ${p.surname}" } Extension functions
  • 13. Collections improvements List<Integer> result = list.stream() .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .collect(Collectors.toList()); val result = list.filter { it != null } List<Integer> result = list.stream() .flatMap(o → o.map(Stream::of) .orElseGet(Stream::empty)) .collect(Collectors.toList()); List<Integer> result = list.stream() .flatMap(Optional::stream) .collect(Collectors.toList());
  • 14. String Interpolation List<Person> persons = Arrays.asList( new Person("Sansa", "Stark"), new Person("Jon", "Snow")); List<String> personNames = persons.stream() .map(p -> p.getName() + " " + p.getSurname()) .collect(Collectors.toList()); val persons = listOf( Person("Sansa", "Stark"), Person("Jon", "Snow")) val personNames = persons .map { p -> "${p.name} ${p.surname}" }
  • 15. Type Inference val persons = listOf( Person("Sansa", "Stark"), Person("Jon", "Snow")) val personNames = persons .map { p -> "${p.name} ${p.surname}" } List<Person> persons = Arrays.asList( new Person("Sansa", "Stark"), new Person("Jon", "Snow")); List<String> personNames = persons.stream() .map(p -> p.getName() + " " + p.getSurname()) .collect(Collectors.toList());
  • 16. Gotcha! Now the idea is trapped inside your head
  • 17. Gotcha! Now the idea is trapped inside your head
  • 18. Gotcha! Now the idea is trapped inside your head
  • 19. 02 LET'S DO IT!
  • 20. Tell the team! The conformist
  • 21. Tell the team! The conformist The idealist
  • 22. Tell the team! The conformist The idealist The responsible
  • 23. Tell the team! The conformist The idealist The responsible AGGG ROOO RAGGAGGG ROOO RAGG ROOOOOOOGHH!ROOOOOOOGHH!
  • 24. What about the rest of the company?
  • 26. Option 2: Talk to them
  • 27. ● Can affect development time ● Misunderstandings can increase bug rate ● Service responsibility is not fixed Not just YOUR team Learning cost
  • 28. ● Learning curve very smooth ● On doubt, use Java style and methods ● Not a real paradigm change ● Same libraries and concepts Learning cost ® BUT...
  • 29. ● Good documentation ● Short library ● Is there a general interest in Kotlin in the company? Kotlin community Android devs pushing for a change Learning cost ® BUT... (2)
  • 30. ● It's production! ● New technology, may have bugs ● Adds code “behind the courtains” ● Any weird behaviour affecting memory, garbage collection... Can affect Performance
  • 31. ● Same Java VM ● You can see compiled bytecode ● Decompile problematic code to Java and tune it ● Start a component in Java and then convert it to Kotlin Can affect Performance ® BUT...
  • 32. ● Extension functions are just a trick, no overhead ● Null checks are a small runtime overhead ● Platform and base libraries are the sane ● Kotlin library overhead not important for backend Can affect Performance ® BUT... (2)
  • 33. ● Increased build time ● Find equivalent tools ● Adaptation to those tools Tooling problems
  • 34. ● Same IDE: IntelliJ, Eclipse... ● Same build tools: Maven, Gradle... ● In a microservices architecture build time not so critical Seconds? Tooling problems ® BUT...
  • 35. ● What if Kotlin stops being “cool”? ● What if nobody uses it anymore? ● What if it just dissapears? Supported / created by Jetbrains Long-term vision
  • 38. ● Development time basically the same ● Code Reviews more interesting! ● Our Java platform was 100% compatible Learning cost?
  • 39. ● Rest of the company? 4 teams doing services in Kotlin Kotlin now official in the company for Android Learning cost?
  • 40. final vs. open Some Java libraries rely on dinamically creating subclasses ● Interceptors and other injection “black magic” Spring, Guice… ● Mocks: Mockito, Spock
  • 41. Compiler plugins ● All-open: Make classes open Shortcut: Spring ● No-args: Create a no-args constructor Shortcut: JPA Beware!: only by annotations
  • 42. Compiler plugins ® All-open not enough ● @Transactional problem (if no class annotation) Explicit open class and methods ● Mocks? Mockito 2.1.0 “inline mocks”: “incubating” Kotlin-runner library: explicit packages
  • 43. Compiler plugins ® No-args not enough ● Object Mapper libraries Explicit no-args constructor ● Spock tests Named parameters don’t work from Java / Groovy
  • 44. const val ONE = 1 // MyObject(1) NO OBJECTS ALLOWED // Translated to: public static final class Constants { companion object { const val TWO = 2 // MyObject(2) NO OBJECTS ALLOWED // Translated to: inlined val THREE = MyObject(3) // Translated to private static // + Companion class with getter @JvmField val FOUR = MyObject(4) // Translated to public static final } } Constants: too many options? https://blog.egorand.me/where-do-i-put-my-constants-in-kotlin/
  • 45. val description: String (type after identifier)
  • 46. val description: String (type after identifier)
  • 48. ● Eclipse with Kotlin and Groovy tests just don’t work ● Eclipse incremental compilation a bit slow ● Some crashes when updating IntelliJ plugin ● Incremental build disabled by default in some versions Maven+Gradle ● Checkstyle, Findbugs… Tooling problems?
  • 49. ● Eclipse with Kotlin and Groovy tests just don’t work ● Eclipse incremental compilation a bit slow ● Some crashes when updating IntelliJ plugin ● Incremental build disabled by default in some versions Maven+Gradle ● Checkstyle, Findbugs… Tooling problems?
  • 51. Functional features fun processPersonName(person: Person?, processor: (String) -> Boolean) = processor( when(person) { null -> "null" is AnonymousPerson -> "anonymous" else -> when { person.isBoss -> "a boss" else -> "the simple ${person.name}" } } )
  • 52. ● Not 100% functional ● Higher kind types ● Typeclasses ● Proposal (KEEP) in discussion to add them, by @raulraja ● Kategory library - http://kategory.io/ Functional paradigm?
  • 53. Black magic companion { [constants: USER_ID, PRODUCTS, OK_RESULT...) } val storeCatalogStub = Stub<StoreCatalog> { getProductsForUserId(USER_ID) <= PRODUCTS } val storeMock = Mock<ProductStore>() val purchaseHistoryMock: PurchaseHistory = Mock() fun `Purchase correct product available in the store`() { given("A valid user") { userService.isValidUser(USER_ID) <= true } `when`("The user tries to do the purchase") { purchaseOperation.perform(USER_ID, PRODUCT_ID) } then("Product is purchased") { 1 * storeMock.purchaseProduct(USER_ID, PRODUCT_ID, null.not()) <= OK_RESULT } and("Operation is logged") { (1..any) * purchaseHistoryMock.logProductPurchased(USER_ID, PRODUCT_ID, any()) } and("No more interactions") { 0 * any } }
  • 54. Black magic companion { [constants: USER_ID, PRODUCTS, OK_RESULT...) } val storeCatalogStub = Stub<StoreCatalog> { getProductsForUserId(USER_ID) <= PRODUCTS } val storeMock = Mock<ProductStore>() val purchaseHistoryMock: PurchaseHistory = Mock() fun `Purchase correct product available in the store`() { given("A valid user") { userService.isValidUser(USER_ID) <= true } `when`("The user tries to do the purchase") { purchaseOperation.perform(USER_ID, PRODUCT_ID) } then("Product is purchased") { 1 * storeMock.purchaseProduct(USER_ID, PRODUCT_ID, null.not()) <= OK_RESULT } and("Operation is logged") { (1..any) * purchaseHistoryMock.logProductPurchased(USER_ID, PRODUCT_ID, any()) } and("No more interactions") { 0 * any } } Lambda param after parenthesis Code generation (compiler plugin)
  • 55. Black magic companion { [constants: USER_ID, PRODUCTS, OK_RESULT...) } val storeCatalogStub = Stub<StoreCatalog> { getProductsForUserId(USER_ID) <= PRODUCTS } val storeMock = Mock<ProductStore>() val purchaseHistoryMock: PurchaseHistory = Mock() fun `Purchase correct product available in the store`() { given("A valid user") { userService.isValidUser(USER_ID) <= true } `when`("The user tries to do the purchase") { purchaseOperation.perform(USER_ID, PRODUCT_ID) } then("Product is purchased") { 1 * storeMock.purchaseProduct(USER_ID, PRODUCT_ID, null.not()) <= OK_RESULT } and("Operation is logged") { (1..any) * purchaseHistoryMock.logProductPurchased(USER_ID, PRODUCT_ID, any()) } and("No more interactions") { 0 * any } } Operator overloading Reified generics Extension functions https://github.com/Koxalen
  • 57. Android ● Anko library ● Consider performance and limits 7k methods (65k methods limit): 10% 380 KB Compilation slower
  • 58. Multi-platform ● Javascript Kotlin wrapper for ReactJS ● Native Kotlin plugin for CLion Kotlin/Native iOS support Not only the JVM! KotlinConf app fully made with Kotlin
  • 60. Yay or Nay? ● Controlled risk, but… worth it? ● What’s the benefit? Mostly syntatic sugar Productivity really improved???
  • 61. Yay or Nay? ● Controlled risk, but… worth it? ● What’s the benefit? Mostly syntatic sugar Productivity really improved??? How about thinking about PEOPLE instead of PRODUCTS?
  • 62. It’s all about LEARNING and MOTIVATION
  • 63.