SlideShare a Scribd company logo
1 of 92
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 & Coach
Founder & Organiser
Bangalore Groovy User Group
http://groovy-lang.org/
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
https://kotlinlang.org/
https://kotlinlang.org/
http://commons.wikimedia.org/wiki/File:You-Are-Here-Earth.png
http://commons.wikimedia.org/wiki/File:You-Are-Here-Earth.png
http://upload.wikimedia.org/wikipedia/commons/4/41/Just_ask_%26_You_are_here_-.jpg
Know your guides
Context/ the Problem
What does “Effective Java” say?
The traps
Idiomatic Solution
Lessons Learned
Tool Wisdom
class Product {
String sku
String description
BigDecimal price
}
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
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
#10: Obey the general contract when
overriding equals
#11: Always override hashCode when
you override equals
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
}
@EqualsAndHashCode
class Product {
String sku
String description
BigDecimal price
}
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
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
@EqualsAndHashCode(includes = 'id')
class Product {
Long id
String sku
String description
BigDecimal price
}
@EqualsAndHashCode(includes = 'id')
class Product {
Long id
String sku
String description
BigDecimal price
}
@EqualsAndHashCode(includes = ‘sku')
class Product {
Long id
String sku
String description
BigDecimal price
}
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
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
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
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
AST Transformation
Single point of representation
of any knowledge
Language / Compiler
#58: Prefer for-each loops to
traditional for loops
def numbers = [10, 20, 30, 40]
def sum = 0
for(int number in numbers){
sum += number
}
println "Sum: " + sum
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
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
Closures/ Higher Order Functions
Favor Internal iterators to
external iterators
Minimise the moving parts
float price = 0.1f;
float total = 0;
for(int i=0; i<10; i++){
total += price;
}
System.out.println("Total: " + total);
Total: 1.0000001
double price = 0.1;
double total = 0;
for(int i=0; i<10; i++){
total += price;
}
System.out.println("Total: " + total);
Total: 0.9999999999999999
#60: Avoid float and double if exact
answers are required
BigDecimal price = new BigDecimal(0.1);
BigDecimal total = new BigDecimal(0);
for(int i=0; i<10; i++){
total = total.add(price);
}
System.out.println("Total: " + total);
Total: 1.0000000000000000555111512312578270211815834045410156250
BigDecimal price = new BigDecimal(0.1);
BigDecimal total = new BigDecimal(0);
for(int i=0; i<10; i++){
total = total.add(price);
}
System.out.println("Total: " + total);
Total: 1.0000000000000000555111512312578270211815834045410156250
def price = 0.1
def total = 0
for(int i=0; i<10; i++){
total += price
}
println "Total: " + total
Total: 1.0
def price = 0.1
def total = 0
for(int i=0; i<10; i++){
total += price
}
println "Total: " + total
println price.class
println total.class
Total: 1.0
class java.math.BigDecimal
class java.math.BigDecimal
Select appropriate defaults
Principle of Least Astonishment
Million Dollar Effort
Million Dollar Effort
null check
List<Speaker> getSpeakers(String conference) {
return null;
}
List<Speaker> j2DaysSpeakers = getSpeakers("Java2Days-2019");
if (j2DaysSpeakers != null) {
//...
}
#54: Return empty arrays or
collections, not nulls
println getSpeakers('Java2Days-2019')
.collect { it.firstName }
println getSpeakers('Java2Days-2019')
.findAll { it.firstName.length() > 5 }
println getSpeakers('Java2Days-2019')
.collect { it.firstName } // []
println getSpeakers('Java2Days-2019')
.findAll { it.firstName.length() > 5 } // []
fun getSpeakers(conference: String): List<Speaker> {
return null
}
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
}
Null can not be a value of a non-null type List<Speaker>
fun getSpeakers(conference: String): List<Speaker>? {
return null
}
NullObject Pattern
No boilerplate code - $$$
Life is too short for null checks!
Type system
#3: Enforce the singleton property
with a private constructor
or an enum type
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
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
@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
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);
}
}
private static Manager manager
static Manager getInstance() {
if(!manager){ manager = new Manager() }
manager
}
private static Manager manager
static synchronized Manager getInstance() {
if(!manager){ manager = new Manager() }
manager
}
private static volatile Manager manager
static synchronized Manager getInstance() {
if(!manager){ manager = new Manager() }
manager
}
@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()
}
}
}
}
AST Transformation
YAGNI
Premature optimisation is the root
of all evil
Object Declaration
https://www.flickr.com/photos/38080114@N07/8594601982/
#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
class ImmutableClass{
private final def field1
private final def field2
//...
private final def field10
public ImmutableClass(f1, f2,… f10){
//initialization
}
}
import groovy.transform.Immutable
@Immutable
class Rectangle {
int length
int breadth
}
def r = new Rectangle(length: 10, breadth: 5)
println r // Rectangle(10, 5)
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)
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
}
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);
}
AST Transformation
Readability Matters
Syntactic Sugar
#18: Favour composition over
inheritance
def ph = ['919812312345', '4512341234', ‘19252199916']
as PhoneNumbers
println ph.find { it == '19252199916'}
println ph.findAll { it.endsWith('4') }
def ph = ['919812312345', '4512341234', '19252199916']
as PhoneNumbers
println ph.find { it == '19252199916'}
println ph.findAll { it.endsWith('4') }
println ph.indianNumbers()
class PhoneNumbers extends ArrayList {
}
class PhoneNumbers {
private @Delegate List phoneNumbers
PhoneNumbers(numbers) {
phoneNumbers = numbers
}
def indianNumbers() {
phoneNumbers.findAll { it.startsWith('91') }
}
}
class PhoneNumbers(val list: List<String>) :
List<String> by list {
fun indianNumbers(): List<String> {
return list.filter { it.startsWith("91") }
}
}
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
AST Transformation
Simplify
Take Aways
Some of the ‘Effective Java’ already
built into the languages
Favour compiler generated cod to
IDE generated code
Don’t fall into the trap of copying the
Java implementation
Programming languages can reduce
friction to implement good practices
There could be multiple right
solutions. Choose what fits your
context
The way we code is influenced not
just by the language we code in,
but also by the languages we
know.
Happy Coding. Thank You

More Related Content

What's hot

C# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD ConversionC# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD ConversionMohammad Shaker
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendSven Efftinge
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...Mario Fusco
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 
How to implement g rpc services in nodejs
How to implement g rpc services in nodejsHow to implement g rpc services in nodejs
How to implement g rpc services in nodejsKaty Slemon
 

What's hot (18)

C# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD ConversionC# Advanced L02-Operator Overloading+Indexers+UD Conversion
C# Advanced L02-Operator Overloading+Indexers+UD Conversion
 
Javaslang @ Devoxx
Javaslang @ DevoxxJavaslang @ Devoxx
Javaslang @ Devoxx
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...How and why I turned my old Java projects into a first-class serverless compo...
How and why I turned my old Java projects into a first-class serverless compo...
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
All about scala
All about scalaAll about scala
All about scala
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
How to implement g rpc services in nodejs
How to implement g rpc services in nodejsHow to implement g rpc services in nodejs
How to implement g rpc services in nodejs
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 

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

Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with GroovyNaresha K
 
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 Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Naresha K
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212Mahmoud Samir Fayed
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup itPROIDEA
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
The Ring programming language version 1.9 book - Part 99 of 210
The Ring programming language version 1.9 book - Part 99 of 210The Ring programming language version 1.9 book - Part 99 of 210
The Ring programming language version 1.9 book - Part 99 of 210Mahmoud Samir Fayed
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming languageSQLI
 
The Ring programming language version 1.5.1 book - Part 175 of 180
The Ring programming language version 1.5.1 book - Part 175 of 180 The Ring programming language version 1.5.1 book - Part 175 of 180
The Ring programming language version 1.5.1 book - Part 175 of 180 Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196Mahmoud Samir Fayed
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx WorkshopDierk König
 

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

Effective Java with Groovy
Effective Java with GroovyEffective Java with Groovy
Effective Java with Groovy
 
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
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
 
The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212The Ring programming language version 1.10 book - Part 17 of 212
The Ring programming language version 1.10 book - Part 17 of 212
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
The Ring programming language version 1.9 book - Part 99 of 210
The Ring programming language version 1.9 book - Part 99 of 210The Ring programming language version 1.9 book - Part 99 of 210
The Ring programming language version 1.9 book - Part 99 of 210
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
The Ring programming language version 1.5.1 book - Part 175 of 180
The Ring programming language version 1.5.1 book - Part 175 of 180 The Ring programming language version 1.5.1 book - Part 175 of 180
The Ring programming language version 1.5.1 book - Part 175 of 180
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196
 
Greach, GroovyFx Workshop
Greach, GroovyFx WorkshopGreach, GroovyFx Workshop
Greach, GroovyFx Workshop
 

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
 
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
 
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
 

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
 
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
 
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
 

Recently uploaded

Lecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptLecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptesrabilgic2
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
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
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
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
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
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
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
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
 

Recently uploaded (20)

Lecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptLecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).ppt
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
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...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
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
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
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
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
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...
 

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 & Coach Founder & Organiser Bangalore Groovy User Group
  • 3.
  • 5. 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
  • 11. Know your guides Context/ the Problem What does “Effective Java” say? The traps Idiomatic Solution Lessons Learned Tool Wisdom
  • 12.
  • 13. class Product { String sku String description BigDecimal price }
  • 14. 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
  • 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) def stock = [:] stock[book1] = 100 println stock[book2] null
  • 16.
  • 17. #10: Obey the general contract when overriding equals #11: Always override hashCode when you override equals
  • 18.
  • 19. 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 }
  • 20. @EqualsAndHashCode class Product { String sku String description BigDecimal price }
  • 21. 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
  • 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) def stock = [:] stock[book1] = 100 println stock[book2] 100
  • 23. @EqualsAndHashCode(includes = 'id') class Product { Long id String sku String description BigDecimal price }
  • 24. @EqualsAndHashCode(includes = 'id') class Product { Long id String sku String description BigDecimal price }
  • 25. @EqualsAndHashCode(includes = ‘sku') class Product { Long id String sku String description BigDecimal price }
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. AST Transformation Single point of representation of any knowledge Language / Compiler
  • 31.
  • 32. #58: Prefer for-each loops to traditional for loops
  • 33. def numbers = [10, 20, 30, 40] def sum = 0 for(int number in numbers){ sum += number } println "Sum: " + sum
  • 34. 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
  • 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. Closures/ Higher Order Functions Favor Internal iterators to external iterators Minimise the moving parts
  • 37. float price = 0.1f; float total = 0; for(int i=0; i<10; i++){ total += price; } System.out.println("Total: " + total); Total: 1.0000001
  • 38. double price = 0.1; double total = 0; for(int i=0; i<10; i++){ total += price; } System.out.println("Total: " + total); Total: 0.9999999999999999
  • 39. #60: Avoid float and double if exact answers are required
  • 40. BigDecimal price = new BigDecimal(0.1); BigDecimal total = new BigDecimal(0); for(int i=0; i<10; i++){ total = total.add(price); } System.out.println("Total: " + total); Total: 1.0000000000000000555111512312578270211815834045410156250
  • 41. BigDecimal price = new BigDecimal(0.1); BigDecimal total = new BigDecimal(0); for(int i=0; i<10; i++){ total = total.add(price); } System.out.println("Total: " + total); Total: 1.0000000000000000555111512312578270211815834045410156250
  • 42. def price = 0.1 def total = 0 for(int i=0; i<10; i++){ total += price } println "Total: " + total Total: 1.0
  • 43. def price = 0.1 def total = 0 for(int i=0; i<10; i++){ total += price } println "Total: " + total println price.class println total.class Total: 1.0 class java.math.BigDecimal class java.math.BigDecimal
  • 44. Select appropriate defaults Principle of Least Astonishment
  • 47. List<Speaker> getSpeakers(String conference) { return null; } List<Speaker> j2DaysSpeakers = getSpeakers("Java2Days-2019"); if (j2DaysSpeakers != null) { //... }
  • 48. #54: Return empty arrays or collections, not nulls
  • 49. println getSpeakers('Java2Days-2019') .collect { it.firstName } println getSpeakers('Java2Days-2019') .findAll { it.firstName.length() > 5 }
  • 50. println getSpeakers('Java2Days-2019') .collect { it.firstName } // [] println getSpeakers('Java2Days-2019') .findAll { it.firstName.length() > 5 } // []
  • 51.
  • 52. fun getSpeakers(conference: String): List<Speaker> { return null }
  • 53. fun getSpeakers(conference: String): List<Speaker> { return null } Null can not be a value of a non-null type List<Speaker>
  • 54. 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 }
  • 55. NullObject Pattern No boilerplate code - $$$ Life is too short for null checks! Type system
  • 56.
  • 57. #3: Enforce the singleton property with a private constructor or an enum type
  • 58. 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
  • 59. 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
  • 60. @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
  • 61. 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); } }
  • 62. private static Manager manager static Manager getInstance() { if(!manager){ manager = new Manager() } manager }
  • 63. private static Manager manager static synchronized Manager getInstance() { if(!manager){ manager = new Manager() } manager }
  • 64. private static volatile Manager manager static synchronized Manager getInstance() { if(!manager){ manager = new Manager() } manager }
  • 65. @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() } } } }
  • 66. AST Transformation YAGNI Premature optimisation is the root of all evil Object Declaration
  • 69. 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
  • 70. class ImmutableClass{ private final def field1 private final def field2 //... private final def field10 public ImmutableClass(f1, f2,… f10){ //initialization } }
  • 71. import groovy.transform.Immutable @Immutable class Rectangle { int length int breadth } def r = new Rectangle(length: 10, breadth: 5) println r // Rectangle(10, 5)
  • 72. 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)
  • 73. 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 }
  • 74. 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); }
  • 76.
  • 77. #18: Favour composition over inheritance
  • 78. def ph = ['919812312345', '4512341234', ‘19252199916'] as PhoneNumbers println ph.find { it == '19252199916'} println ph.findAll { it.endsWith('4') }
  • 79. def ph = ['919812312345', '4512341234', '19252199916'] as PhoneNumbers println ph.find { it == '19252199916'} println ph.findAll { it.endsWith('4') } println ph.indianNumbers()
  • 80. class PhoneNumbers extends ArrayList { }
  • 81. class PhoneNumbers { private @Delegate List phoneNumbers PhoneNumbers(numbers) { phoneNumbers = numbers } def indianNumbers() { phoneNumbers.findAll { it.startsWith('91') } } }
  • 82. class PhoneNumbers(val list: List<String>) : List<String> by list { fun indianNumbers(): List<String> { return list.filter { it.startsWith("91") } } }
  • 83. 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
  • 86. Some of the ‘Effective Java’ already built into the languages
  • 87. Favour compiler generated cod to IDE generated code
  • 88. Don’t fall into the trap of copying the Java implementation
  • 89. Programming languages can reduce friction to implement good practices
  • 90. There could be multiple right solutions. Choose what fits your context
  • 91. The way we code is influenced not just by the language we code in, but also by the languages we know.