SlideShare a Scribd company logo
1 of 85
Download to read offline
Effective Java
with Groovy & Kotlin
How Languages Influence Adoption of Good
Practices
Naresha K

@naresha_k

https://blog.nareshak.com/
About me
Developer, Architect &
Tech Excellence Coach
Founder & Organiser
Bangalore Groovy User
Group
3
Java Language
JVM
Platform/ Real Machine Platform/ Real Machine Platform/ Real Machine
4
Java Language
Platform/ Real Machine Platform/ Real Machine Platform/ Real Machine
Groovy
JVM
5
Java Language
Platform/ Real Machine Platform/ Real Machine Platform/ Real Machine
Groovy Kotlin
JVM
6
Most people talk about Java the language,
and this may sound odd coming from me,
but I could hardly care less. At the core of
the Java ecosystem is the JVM.
- James Gosling,
Creator of the Java Programming Language(2011, TheServerSide)
7
8
http://groovy-lang.org/
9
initial idea was to make a little
dynamic language which compiles
directly to Java classes and provides
all the nice (alleged) productivity
benefits
- James Strachan
http://radio-weblogs.com/0112098/2003/08/29.html
10
https://kotlinlang.org/
11
https://kotlinlang.org/
Know your guides
Context/ the Problem
What does “Effective Java” say?
The traps
Idiomatic Solution
Lessons Learned
Tool Wisdom
12
13
14
class Product {
String sku
String description
BigDecimal price
}
15
Product book1 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
Product book2 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
println book1 == book2
false
16
Product book1 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
Product book2 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
def stock = [:]
stock[book1] = 100
println stock[book2]
null
17
18
#10: Obey the general contract when
overriding equals
#11: Always override hashCode when
you override equals
19
20
class Product {
String sku
String description
BigDecimal price
}
class Product {
String sku
String description
BigDecimal price
LocalDate dateOfManufacture
} class Product {
String sku
String description
BigDecimal price
LocalDate dateOfManufacture
LocalDate dateOfExpiry
}
21
@EqualsAndHashCode
class Product {
String sku
String description
BigDecimal price
}
22
Product book1 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
Product book2 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
println book1 == book2
true
23
Product book1 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
Product book2 = new Product(
sku: 'P101',
description: 'Effective Java’,
price: 40.0)
def stock = [:]
stock[book1] = 100
println stock[book2]
100
24
@EqualsAndHashCode(includes = 'id')
class Product {
Long id
String sku
String description
BigDecimal price
}
25
@EqualsAndHashCode(includes = 'id')
class Product {
Long id
String sku
String description
BigDecimal price
}
26
@EqualsAndHashCode(includes = ‘sku')
class Product {
Long id
String sku
String description
BigDecimal price
}
27
class Product(val sku: String, val description: String,
val price: BigDecimal)
fun main() {
val book1 = Product("P101", "Effective Java", BigDecimal("35.08"))
val book2 = Product("P101", "Effective Java", BigDecimal("35.08"))
println(book1 == book2)
val stock = mapOf(book1 to 100)
println(stock[book2])
}
false
null
28
data class Product(val sku: String, val description: String, val price:
BigDecimal)
fun main() {
val book1 = Product("P101", "Effective Java", BigDecimal("35.08"))
val book2 = Product("P101", "Effective Java", BigDecimal("35.08"))
println(book1 == book2)
val stock = mapOf(book1 to 100)
println(stock[book2])
}
true
100
29
data class Product(val sku: String, val description: String,
val price: BigDecimal, var id: Long?)
fun main() {
val book1 = Product("P101", "Effective Java", BigDecimal("35.08"), null)
val book2 = Product("P101", "Effective Java", BigDecimal("35.08"), 1L)
println(book1 == book2)
val stock = mapOf(book1 to 100)
println(stock[book2])
}
false
null
30
data class Product(val sku: String, val description: String, val price:
BigDecimal) {
var id: Long? = null
}
fun main() {
val book1 = Product("P101", "Effective Java", BigDecimal("35.08"))
val book2 = Product("P101", "Effective Java", BigDecimal("35.08"))
book2.id = 1L
println(book1 == book2)
val stock = mapOf(book1 to 100)
println(stock[book2])
}
true
100
31
AST Transformation
Single point of representation
of any knowledge
Language / Compiler
32
33
List<String> languages = List.of("Java", "Groovy", "Kotlin");
for (int i = 0; i < languages.size(); i++) {
System.out.println(languages.get(i));
}
for (String language : languages) {
System.out.println(language);
}
34
#58: Prefer for-each loops to
traditional for loops
35
numbers.forEach {
println(it)
}
println(numbers.map {
it * 2
})
println(numbers.fold(0)
{ acc, number -> acc + number })
10
20
30
40
[20, 40, 60, 80]
100
36
numbers.each { number ->
println number
}
println numbers.collect { number ->
number * 2
}
println numbers.inject(0,
{ result, number -> result + number }
)
10
20
30
40
[20, 40, 60, 80]
100
37
Closures/ Higher Order Functions
Favor Internal iterators to
external iterators
Minimise the moving parts
38
Million Dollar Effort
39
Million Dollar Effort
null check
40
List<Speaker> getSpeakers(String conference) {
return null;
}
List<Speaker> speakers = getSpeakers(“I Code Java Africa");
if (speakers != null) {
//...
}
41
#54: Return empty arrays or
collections, not nulls
42
println getSpeakers('I Code Java Africa')
.collect { it.firstName }
println getSpeakers('I Code Java Africa')
.findAll { it.firstName.length() > 5 }
43
println getSpeakers('I Code Java Africa')
.collect { it.firstName } // []
println getSpeakers('I Code Java Africa')
.findAll { it.firstName.length() > 5 } // []
44
45
fun getSpeakers(conference: String): List<Speaker> {
return null
}
46
fun getSpeakers(conference: String): List<Speaker> {
return null
}
Null can not be a value of a non-null type List<Speaker>
47
fun getSpeakers(conference: String): List<Speaker> {
return null
}
Null can not be a value of a non-null type List<Speaker>
fun getSpeakers(conference: String): List<Speaker>? {
return null
}
48
NullObject Pattern
No boilerplate code - $$$
Life is too short for null checks!
Type system
49
https://www.flickr.com/photos/38080114@N07/8594601982/
50
#17: Minimize Mutability
Rules to make a class immutable
1. Don’t provide any mutators
2. Ensure that the class can’t be extended
3. Make all fields final
4. Make all fields private
5. Ensure exclusive access to any mutable
components
52
class ImmutableClass{
private final def field1
private final def field2
//...
private final def field10
public ImmutableClass(f1, f2,… f10){
//initialization
}
}
53
import groovy.transform.Immutable
@Immutable
class Rectangle {
int length
int breadth
}
def r = new Rectangle(length: 10, breadth: 5)
println r // Rectangle(10, 5)
54
public final class Rectangle extends java.lang.Object
implements groovy.lang.GroovyObject {
private final int length
private final int breadth
public Rectangle(int length, int breadth) {
//
}
public Rectangle(java.util.Map args) {
}
public Rectangle() {
this([:])
}
}
new Rectangle(length: 10, breadth: 5)
55
data class Rectangle(val length: Int, val breadth: Int)
public final class Rectangle {
private final int length;
private final int breadth;
public final int getLength() {
return this.length;
}
public final int getBreadth() {
return this.breadth;
}
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
// more code
}
56
data class Rectangle(val length: Int, val breadth: Int)
fun main() {
val rectangle = Rectangle(20, 10)
val r2 = Rectangle(length = 20, breadth = 10)
}
public static final void main() {
Rectangle rectangle = new Rectangle(20, 10);
Rectangle r2 = new Rectangle(20, 10);
}
57
AST Transformation
Readability Matters
Syntactic Sugar
58
59
#18: Favour composition over
inheritance
60
def ph = ['919812312345', '4512341234', ‘19252199916']
as PhoneNumbers
println ph.find { it == '19252199916'}
println ph.findAll { it.endsWith('4') }
61
def ph = ['919812312345', '4512341234', '19252199916']
as PhoneNumbers
println ph.find { it == '19252199916'}
println ph.findAll { it.endsWith('4') }
println ph.indianNumbers()
62
class PhoneNumbers extends ArrayList {
}
63
class PhoneNumbers {
private @Delegate List phoneNumbers
PhoneNumbers(numbers) {
phoneNumbers = numbers
}
def indianNumbers() {
phoneNumbers.findAll { it.startsWith('91') }
}
}
64
class PhoneNumbers(val list: List<String>) :
List<String> by list {
fun indianNumbers(): List<String> {
return list.filter { it.startsWith("91") }
}
}
65
trait CanSing {
def sing() {
println "Singing"
}
}
trait CanDance {
def dance() {
println "Dancing"
}
}
class Person implements CanSing, CanDance {}
Person reema = new Person()
reema.sing()
reema.dance()
https://www.slideshare.net/nareshak/designing-with-groovy-traits-gr8conf-india
66
AST Transformation
Simplify
67
68
#3: Enforce the singleton property
with a private constructor
or an enum type
69
class Manager {
private static final Manager manager =
new Manager()
private Manager() { super() }
static Manager getInstance() { manager }
}
def m1 = Manager.getInstance()
def m2 = Manager.getInstance()
println m1 == m2
true
70
class Manager {
private static final Manager manager =
new Manager()
private Manager() { super() }
static Manager getInstance() { manager }
}
def m1 = Manager.getInstance()
def m2 = Manager.getInstance()
println m1 == m2
true
def m3 = new Manager()
println m3 Manager@b968a76
71
@Singleton
class Manager {}
def m1 = Manager.getInstance()
def m2 = Manager.getInstance()
println m1 == m2
def m3 = new Manager()
println m3
true
Caught: java.lang.RuntimeException: Can't instantiate singleton Manager.
Use Manager.instance
72
object Manager {
init {
println("Initialising Manager")
}
}
public final class Manager {
public static final Manager INSTANCE;
private Manager() {
}
static {
Manager var0 = new Manager();
INSTANCE = var0;
String var1 = "Initialising Manager";
boolean var2 = false;
System.out.println(var1);
}
}
73
private static Manager manager
static Manager getInstance() {
if(!manager){ manager = new Manager() }
manager
}
74
private static Manager manager
static synchronized Manager getInstance() {
if(!manager){ manager = new Manager() }
manager
}
75
private static volatile Manager manager
static synchronized Manager getInstance() {
if(!manager){ manager = new Manager() }
manager
}
76
@Singleton(lazy=true)
class Manager {}
public static Manager getInstance() {
if (instance != null) {
return instance
} else {
synchronized (Manager) {
if (instance != null) {
return instance
} else {
return instance = new Manager()
}
}
}
}
77
AST Transformation
YAGNI
Premature optimisation is the root
of all evil
Object Declaration
78
Take Aways
79
Some of the ‘Effective Java’ already
built into the languages
80
Favour compiler generated code to
IDE generated code
81
Don’t fall into the trap of copying the
Java implementation
82
Programming languages can reduce
friction to implement good practices
83
There could be multiple right
solutions. Choose what fits your
context
84
The way we code is influenced not
just by the language we code in,
but also by the languages we
know.
85
Happy Coding. Thank You

More Related Content

What's hot

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesAbhishek Sur
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesNaresha K
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode CompilerDonal Fellows
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVMAndres Almiray
 
Nik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReactNik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReactOdessaJS Conf
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Chang W. Doh
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185Mahmoud Samir Fayed
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languagePawel Szulc
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?Chang W. Doh
 

What's hot (20)

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
C# 7
C# 7C# 7
C# 7
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Effective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good PracticesEffective Java with Groovy - How Language can Influence Good Practices
Effective Java with Groovy - How Language can Influence Good Practices
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVM
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Nik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReactNik Graf - Get started with Reason and ReasonReact
Nik Graf - Get started with Reason and ReasonReact
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189The Ring programming language version 1.6 book - Part 184 of 189
The Ring programming language version 1.6 book - Part 184 of 189
 
The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185The Ring programming language version 1.5.4 book - Part 32 of 185
The Ring programming language version 1.5.4 book - Part 32 of 185
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Hey Kotlin, How it works?
Hey Kotlin, How it works?Hey Kotlin, How it works?
Hey Kotlin, How it works?
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 

Similar to Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Good Practices

Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesNaresha K
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Naresha K
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvmArnaud Giuliani
 
JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011Stephen Chin
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle ScalaSlim Ouertani
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Codemotion
 
JavaFX Your Way - Devoxx Version
JavaFX Your Way - Devoxx VersionJavaFX Your Way - Devoxx Version
JavaFX Your Way - Devoxx VersionStephen Chin
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Davide Cerbo
 
JavaFX 2.0 and Alternative Languages
JavaFX 2.0 and Alternative LanguagesJavaFX 2.0 and Alternative Languages
JavaFX 2.0 and Alternative LanguagesStephen Chin
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma CloudNikolas Burk
 
Kotlin: maybe it's the right time
Kotlin: maybe it's the right timeKotlin: maybe it's the right time
Kotlin: maybe it's the right timeDavide Cerbo
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with GroovyNaresha K
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
JavaFX Your Way: Building JavaFX Applications with Alternative Languages
JavaFX Your Way: Building JavaFX Applications with Alternative LanguagesJavaFX Your Way: Building JavaFX Applications with Alternative Languages
JavaFX Your Way: Building JavaFX Applications with Alternative LanguagesStephen Chin
 
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...Stephen Chin
 
Why Scala is the better Java
Why Scala is the better JavaWhy Scala is the better Java
Why Scala is the better JavaThomas Kaiser
 
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...Stephen Chin
 

Similar to Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Good Practices (20)

Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good Practices
 
JavaFX
JavaFXJavaFX
JavaFX
 
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
JavaFX Your Way - Devoxx Version
JavaFX Your Way - Devoxx VersionJavaFX Your Way - Devoxx Version
JavaFX Your Way - Devoxx Version
 
Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)Kotlin: forse è la volta buona (Trento)
Kotlin: forse è la volta buona (Trento)
 
JavaFX 2.0 and Alternative Languages
JavaFX 2.0 and Alternative LanguagesJavaFX 2.0 and Alternative Languages
JavaFX 2.0 and Alternative Languages
 
Managing GraphQL servers with AWS Fargate & Prisma Cloud
Managing GraphQL servers  with AWS Fargate & Prisma CloudManaging GraphQL servers  with AWS Fargate & Prisma Cloud
Managing GraphQL servers with AWS Fargate & Prisma Cloud
 
Scala intro workshop
Scala intro workshopScala intro workshop
Scala intro workshop
 
Kotlin: maybe it's the right time
Kotlin: maybe it's the right timeKotlin: maybe it's the right time
Kotlin: maybe it's the right time
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
JavaFX Your Way: Building JavaFX Applications with Alternative Languages
JavaFX Your Way: Building JavaFX Applications with Alternative LanguagesJavaFX Your Way: Building JavaFX Applications with Alternative Languages
JavaFX Your Way: Building JavaFX Applications with Alternative Languages
 
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
 
Why Scala is the better Java
Why Scala is the better JavaWhy Scala is the better Java
Why Scala is the better Java
 
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
JavaFX 2.0 With Alternative Languages - Groovy, Clojure, Scala, Fantom, and V...
 

More from Naresha K

The Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockThe Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockNaresha K
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveNaresha K
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersNaresha K
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with MicronautNaresha K
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersNaresha K
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy WayNaresha K
 
What's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingWhat's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingNaresha K
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...Naresha K
 
Implementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautImplementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautNaresha K
 
Groovy - Why and Where?
Groovy  - Why and Where?Groovy  - Why and Where?
Groovy - Why and Where?Naresha K
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaNaresha K
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring PatternsNaresha K
 
Implementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautImplementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautNaresha K
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveNaresha K
 
Beyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaBeyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaNaresha K
 
GORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitGORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitNaresha K
 
Rethinking HTTP Apps using Ratpack
Rethinking HTTP Apps using RatpackRethinking HTTP Apps using Ratpack
Rethinking HTTP Apps using RatpackNaresha K
 
Design Patterns from 10K feet
Design Patterns from 10K feetDesign Patterns from 10K feet
Design Patterns from 10K feetNaresha K
 
Java beyond Java - from the language to platform
Java beyond Java - from the language to platformJava beyond Java - from the language to platform
Java beyond Java - from the language to platformNaresha K
 
Think beyond frameworks, The real gems are in the languages
Think beyond frameworks, The real gems are in the languagesThink beyond frameworks, The real gems are in the languages
Think beyond frameworks, The real gems are in the languagesNaresha K
 

More from Naresha K (20)

The Groovy Way of Testing with Spock
The Groovy Way of Testing with SpockThe Groovy Way of Testing with Spock
The Groovy Way of Testing with Spock
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Implementing Resilience with Micronaut
Implementing Resilience with MicronautImplementing Resilience with Micronaut
Implementing Resilience with Micronaut
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Favouring Composition - The Groovy Way
Favouring Composition - The Groovy WayFavouring Composition - The Groovy Way
Favouring Composition - The Groovy Way
 
What's in Groovy for Functional Programming
What's in Groovy for Functional ProgrammingWhat's in Groovy for Functional Programming
What's in Groovy for Functional Programming
 
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...Eclipse Collections, Java Streams & Vavr - What's in them for  Functional Pro...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
 
Implementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with MicronautImplementing Cloud-Native Architectural Patterns with Micronaut
Implementing Cloud-Native Architectural Patterns with Micronaut
 
Groovy - Why and Where?
Groovy  - Why and Where?Groovy  - Why and Where?
Groovy - Why and Where?
 
Leveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS LambdaLeveraging Micronaut on AWS Lambda
Leveraging Micronaut on AWS Lambda
 
Groovy Refactoring Patterns
Groovy Refactoring PatternsGroovy Refactoring Patterns
Groovy Refactoring Patterns
 
Implementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with MicronautImplementing Cloud-native Architectural Patterns with Micronaut
Implementing Cloud-native Architectural Patterns with Micronaut
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
Beyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in JavaBeyond Lambdas & Streams - Functional Fluency in Java
Beyond Lambdas & Streams - Functional Fluency in Java
 
GORM - The polyglot data access toolkit
GORM - The polyglot data access toolkitGORM - The polyglot data access toolkit
GORM - The polyglot data access toolkit
 
Rethinking HTTP Apps using Ratpack
Rethinking HTTP Apps using RatpackRethinking HTTP Apps using Ratpack
Rethinking HTTP Apps using Ratpack
 
Design Patterns from 10K feet
Design Patterns from 10K feetDesign Patterns from 10K feet
Design Patterns from 10K feet
 
Java beyond Java - from the language to platform
Java beyond Java - from the language to platformJava beyond Java - from the language to platform
Java beyond Java - from the language to platform
 
Think beyond frameworks, The real gems are in the languages
Think beyond frameworks, The real gems are in the languagesThink beyond frameworks, The real gems are in the languages
Think beyond frameworks, The real gems are in the languages
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Good Practices

  • 1. Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good Practices Naresha K @naresha_k https://blog.nareshak.com/
  • 2. About me Developer, Architect & Tech Excellence Coach Founder & Organiser Bangalore Groovy User Group
  • 3. 3 Java Language JVM Platform/ Real Machine Platform/ Real Machine Platform/ Real Machine
  • 4. 4 Java Language Platform/ Real Machine Platform/ Real Machine Platform/ Real Machine Groovy JVM
  • 5. 5 Java Language Platform/ Real Machine Platform/ Real Machine Platform/ Real Machine Groovy Kotlin JVM
  • 6. 6 Most people talk about Java the language, and this may sound odd coming from me, but I could hardly care less. At the core of the Java ecosystem is the JVM. - James Gosling, Creator of the Java Programming Language(2011, TheServerSide)
  • 7. 7
  • 9. 9 initial idea was to make a little dynamic language which compiles directly to Java classes and provides all the nice (alleged) productivity benefits - James Strachan http://radio-weblogs.com/0112098/2003/08/29.html
  • 12. Know your guides Context/ the Problem What does “Effective Java” say? The traps Idiomatic Solution Lessons Learned Tool Wisdom 12
  • 13. 13
  • 14. 14 class Product { String sku String description BigDecimal price }
  • 15. 15 Product book1 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) Product book2 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) println book1 == book2 false
  • 16. 16 Product book1 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) Product book2 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) def stock = [:] stock[book1] = 100 println stock[book2] null
  • 17. 17
  • 18. 18 #10: Obey the general contract when overriding equals #11: Always override hashCode when you override equals
  • 19. 19
  • 20. 20 class Product { String sku String description BigDecimal price } class Product { String sku String description BigDecimal price LocalDate dateOfManufacture } class Product { String sku String description BigDecimal price LocalDate dateOfManufacture LocalDate dateOfExpiry }
  • 21. 21 @EqualsAndHashCode class Product { String sku String description BigDecimal price }
  • 22. 22 Product book1 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) Product book2 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) println book1 == book2 true
  • 23. 23 Product book1 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) Product book2 = new Product( sku: 'P101', description: 'Effective Java’, price: 40.0) def stock = [:] stock[book1] = 100 println stock[book2] 100
  • 24. 24 @EqualsAndHashCode(includes = 'id') class Product { Long id String sku String description BigDecimal price }
  • 25. 25 @EqualsAndHashCode(includes = 'id') class Product { Long id String sku String description BigDecimal price }
  • 26. 26 @EqualsAndHashCode(includes = ‘sku') class Product { Long id String sku String description BigDecimal price }
  • 27. 27 class Product(val sku: String, val description: String, val price: BigDecimal) fun main() { val book1 = Product("P101", "Effective Java", BigDecimal("35.08")) val book2 = Product("P101", "Effective Java", BigDecimal("35.08")) println(book1 == book2) val stock = mapOf(book1 to 100) println(stock[book2]) } false null
  • 28. 28 data class Product(val sku: String, val description: String, val price: BigDecimal) fun main() { val book1 = Product("P101", "Effective Java", BigDecimal("35.08")) val book2 = Product("P101", "Effective Java", BigDecimal("35.08")) println(book1 == book2) val stock = mapOf(book1 to 100) println(stock[book2]) } true 100
  • 29. 29 data class Product(val sku: String, val description: String, val price: BigDecimal, var id: Long?) fun main() { val book1 = Product("P101", "Effective Java", BigDecimal("35.08"), null) val book2 = Product("P101", "Effective Java", BigDecimal("35.08"), 1L) println(book1 == book2) val stock = mapOf(book1 to 100) println(stock[book2]) } false null
  • 30. 30 data class Product(val sku: String, val description: String, val price: BigDecimal) { var id: Long? = null } fun main() { val book1 = Product("P101", "Effective Java", BigDecimal("35.08")) val book2 = Product("P101", "Effective Java", BigDecimal("35.08")) book2.id = 1L println(book1 == book2) val stock = mapOf(book1 to 100) println(stock[book2]) } true 100
  • 31. 31 AST Transformation Single point of representation of any knowledge Language / Compiler
  • 32. 32
  • 33. 33 List<String> languages = List.of("Java", "Groovy", "Kotlin"); for (int i = 0; i < languages.size(); i++) { System.out.println(languages.get(i)); } for (String language : languages) { System.out.println(language); }
  • 34. 34 #58: Prefer for-each loops to traditional for loops
  • 35. 35 numbers.forEach { println(it) } println(numbers.map { it * 2 }) println(numbers.fold(0) { acc, number -> acc + number }) 10 20 30 40 [20, 40, 60, 80] 100
  • 36. 36 numbers.each { number -> println number } println numbers.collect { number -> number * 2 } println numbers.inject(0, { result, number -> result + number } ) 10 20 30 40 [20, 40, 60, 80] 100
  • 37. 37 Closures/ Higher Order Functions Favor Internal iterators to external iterators Minimise the moving parts
  • 40. 40 List<Speaker> getSpeakers(String conference) { return null; } List<Speaker> speakers = getSpeakers(“I Code Java Africa"); if (speakers != null) { //... }
  • 41. 41 #54: Return empty arrays or collections, not nulls
  • 42. 42 println getSpeakers('I Code Java Africa') .collect { it.firstName } println getSpeakers('I Code Java Africa') .findAll { it.firstName.length() > 5 }
  • 43. 43 println getSpeakers('I Code Java Africa') .collect { it.firstName } // [] println getSpeakers('I Code Java Africa') .findAll { it.firstName.length() > 5 } // []
  • 44. 44
  • 45. 45 fun getSpeakers(conference: String): List<Speaker> { return null }
  • 46. 46 fun getSpeakers(conference: String): List<Speaker> { return null } Null can not be a value of a non-null type List<Speaker>
  • 47. 47 fun getSpeakers(conference: String): List<Speaker> { return null } Null can not be a value of a non-null type List<Speaker> fun getSpeakers(conference: String): List<Speaker>? { return null }
  • 48. 48 NullObject Pattern No boilerplate code - $$$ Life is too short for null checks! Type system
  • 51. Rules to make a class immutable 1. Don’t provide any mutators 2. Ensure that the class can’t be extended 3. Make all fields final 4. Make all fields private 5. Ensure exclusive access to any mutable components
  • 52. 52 class ImmutableClass{ private final def field1 private final def field2 //... private final def field10 public ImmutableClass(f1, f2,… f10){ //initialization } }
  • 53. 53 import groovy.transform.Immutable @Immutable class Rectangle { int length int breadth } def r = new Rectangle(length: 10, breadth: 5) println r // Rectangle(10, 5)
  • 54. 54 public final class Rectangle extends java.lang.Object implements groovy.lang.GroovyObject { private final int length private final int breadth public Rectangle(int length, int breadth) { // } public Rectangle(java.util.Map args) { } public Rectangle() { this([:]) } } new Rectangle(length: 10, breadth: 5)
  • 55. 55 data class Rectangle(val length: Int, val breadth: Int) public final class Rectangle { private final int length; private final int breadth; public final int getLength() { return this.length; } public final int getBreadth() { return this.breadth; } public Rectangle(int length, int breadth) { this.length = length; this.breadth = breadth; } // more code }
  • 56. 56 data class Rectangle(val length: Int, val breadth: Int) fun main() { val rectangle = Rectangle(20, 10) val r2 = Rectangle(length = 20, breadth = 10) } public static final void main() { Rectangle rectangle = new Rectangle(20, 10); Rectangle r2 = new Rectangle(20, 10); }
  • 58. 58
  • 59. 59 #18: Favour composition over inheritance
  • 60. 60 def ph = ['919812312345', '4512341234', ‘19252199916'] as PhoneNumbers println ph.find { it == '19252199916'} println ph.findAll { it.endsWith('4') }
  • 61. 61 def ph = ['919812312345', '4512341234', '19252199916'] as PhoneNumbers println ph.find { it == '19252199916'} println ph.findAll { it.endsWith('4') } println ph.indianNumbers()
  • 63. 63 class PhoneNumbers { private @Delegate List phoneNumbers PhoneNumbers(numbers) { phoneNumbers = numbers } def indianNumbers() { phoneNumbers.findAll { it.startsWith('91') } } }
  • 64. 64 class PhoneNumbers(val list: List<String>) : List<String> by list { fun indianNumbers(): List<String> { return list.filter { it.startsWith("91") } } }
  • 65. 65 trait CanSing { def sing() { println "Singing" } } trait CanDance { def dance() { println "Dancing" } } class Person implements CanSing, CanDance {} Person reema = new Person() reema.sing() reema.dance() https://www.slideshare.net/nareshak/designing-with-groovy-traits-gr8conf-india
  • 67. 67
  • 68. 68 #3: Enforce the singleton property with a private constructor or an enum type
  • 69. 69 class Manager { private static final Manager manager = new Manager() private Manager() { super() } static Manager getInstance() { manager } } def m1 = Manager.getInstance() def m2 = Manager.getInstance() println m1 == m2 true
  • 70. 70 class Manager { private static final Manager manager = new Manager() private Manager() { super() } static Manager getInstance() { manager } } def m1 = Manager.getInstance() def m2 = Manager.getInstance() println m1 == m2 true def m3 = new Manager() println m3 Manager@b968a76
  • 71. 71 @Singleton class Manager {} def m1 = Manager.getInstance() def m2 = Manager.getInstance() println m1 == m2 def m3 = new Manager() println m3 true Caught: java.lang.RuntimeException: Can't instantiate singleton Manager. Use Manager.instance
  • 72. 72 object Manager { init { println("Initialising Manager") } } public final class Manager { public static final Manager INSTANCE; private Manager() { } static { Manager var0 = new Manager(); INSTANCE = var0; String var1 = "Initialising Manager"; boolean var2 = false; System.out.println(var1); } }
  • 73. 73 private static Manager manager static Manager getInstance() { if(!manager){ manager = new Manager() } manager }
  • 74. 74 private static Manager manager static synchronized Manager getInstance() { if(!manager){ manager = new Manager() } manager }
  • 75. 75 private static volatile Manager manager static synchronized Manager getInstance() { if(!manager){ manager = new Manager() } manager }
  • 76. 76 @Singleton(lazy=true) class Manager {} public static Manager getInstance() { if (instance != null) { return instance } else { synchronized (Manager) { if (instance != null) { return instance } else { return instance = new Manager() } } } }
  • 77. 77 AST Transformation YAGNI Premature optimisation is the root of all evil Object Declaration
  • 79. 79 Some of the ‘Effective Java’ already built into the languages
  • 80. 80 Favour compiler generated code to IDE generated code
  • 81. 81 Don’t fall into the trap of copying the Java implementation
  • 82. 82 Programming languages can reduce friction to implement good practices
  • 83. 83 There could be multiple right solutions. Choose what fits your context
  • 84. 84 The way we code is influenced not just by the language we code in, but also by the languages we know.