42. Bring in Order
!42
@ToString
class Person {
String name
int age
}
def geeks = [
new Person(name: 'Arun', age: 35),
new Person(name: 'Raj', age: 30),
new Person(name: 'Abhi', age: 35),
new Person(name:'Kumar', age: 32),
new Person(name: 'Kumar', age: 25)
]
47. Sort by Age
!47
println geeks.sort(false) { a, b -> a.age <=> b.age}
Original:
[
Person(Arun, 35),
Person(Raj, 30),
Person(Abhi, 35),
Person(Kumar, 32),
Person(Kumar, 25)
]
Sorted:
[
Person(Kumar, 25),
Person(Raj, 30),
Person(Kumar, 32),
Person(Arun, 35),
Person(Abhi, 35)
]
48. Sort by age, name
!48
int compareTo(Person other) {
if (this.is(other)) {
return 0
}
java.lang.Integer value = 0
value = this .name <=> other .name
if ( value != 0) {
return value
}
value = this .age <=> other .age
if ( value != 0) {
return value
}
return 0
}
49. Sort by age, name
!49
println geeks.sort(false, { a, b ->
[{it.age}, {it.name}].findResult { c ->
c(a) <=> c(b) ?: null
}
})
Original:
[
Person(Arun, 35),
Person(Raj, 30),
Person(Abhi, 35),
Person(Kumar, 32),
Person(Kumar, 25)
]
Sorted:
[
Person(Kumar, 25),
Person(Raj, 30),
Person(Kumar, 32),
Person(Abhi, 35),
Person(Arun, 35)
]
50. Sort by age, name
!50
Original:
[
Person(Arun, 35),
Person(Raj, 30),
Person(Abhi, 35),
Person(Kumar, 32),
Person(Kumar, 25)
]
Sorted:
[
Person(Kumar, 25),
Person(Raj, 30),
Person(Kumar, 32),
Person(Abhi, 35),
Person(Arun, 35)
]
@Sortable(includes = "name, age")
@ToString
class Person {
String name
int age
}
63. !63
class Manager{
private static final Manager manager =
new Manager()
private Manager(){ super() }
static Manager getInstance(){ manager }
}
def m = new Manager()
println m Manager@12e61fe6
64. !64
@Singleton
class Manager{
}
def m1 = Manager.getInstance()
def m2 = Manager.getInstance()
println m1 == m2
def m = new Manager()
println m
Caught: java.lang.RuntimeException: Can't instantiate singleton Manager.
Use Manager.instance
74. Rules to make a class mutable
• Don’t provide any mutators
• Ensure that the class can’t be extended
• Make all fields final
• Make all fields private
• Ensure exclusive access to any mutable components
!74
75. !75
class ImmutableClass{
private final def field1
private final def field2
//...
private final def field10
public ImmutableClass(f1, f2,… f10){
//initialization
}
}
86. Take Away
Some of the ‘Effective Java’ already built into
the language
AST Transformations reduce the effort to
implement few more
Effective Java implementations may not always be
effective Groovy implementations (Traps)
!86