SlideShare a Scribd company logo
CLEANER & LEANER
GROOVY!
© Rowell Belen
@BUILDER
@Builder
class Premise {
def sqFeet
def occupants
def stories
def heatingType
def coolingType
def homeType
def yearBuilt
}
def premise = Premise.builder()
.sqFeet(1200)
.occupants(4)
.stories(2)
.heatingType('Furnace·(Gas)')
.coolingType('Central·Air·Conditioning')
.homeType('Single·Family·(detached)')
.yearBuilt(1995).build()
© Rowell Belen
@TOSTRING
@ToString(includeNames=true, ignoreNulls = true, excludes="ssn")
class Customer {
String first, last
int age
Collection favItems
String ssn
}
def customer =
new Customer(first:'Tom', last:'Jones', age:21, favItems:['Books', 'Games'], ssn:'xxx-xx-xxxxx')
assert customer.toString() ==
'Customer(first:Tom, last:Jones, age:21, favItems:[Books, Games])'
© Rowell Belen
@EQUALSANDHASHCODE
@EqualsAndHashCode
class Actor {
String firstName, lastName
}
def magneto = new Actor(firstName:'Ian', lastName: 'McKellen')
def gandalf = new Actor(firstName:'Ian', lastName: 'McKellen')
assert magneto == gandalf
© Rowell Belen
@TUPLECONSTRUCTOR
import groovy.transform.TupleConstructor
@TupleConstructor
class Athlete {
String firstName, lastName
}
def a1 = new Athlete('Michael', 'Jordan')
def a2 = new Athlete('Michael')
assert a1.firstName == a2.firstName
© Rowell Belen
@LAZY
class App {
@Lazy
AuthService authService = { ctx.getBean('AuthService.class') }()
@Lazy // defer expensive initialization
ApplicationContext ctx =
{ new AnnotationConfigApplicationContext(AppConfig.class) }()
@Lazy
UserService userService
Profile getProfile(user){
authService.login(user)
userService.findProfile(user)
}
}
© Rowell Belen
@IMMUTABLE
@Immutable
class User {
String email
Collection roles
}
def u = new User(email: 'email@host.com', roles: ['admin', 'user'])
// Properties are readonly.
shouldFail(ReadOnlyPropertyException) {
u.email = 'new@email.com'
}
// Collections are also wrapped in immutable wrapper classes
shouldFail(UnsupportedOperationException) {
u.roles << 'new role'
}
© Rowell Belen
@SINGLETON
@Singleton
class Zeus {
...
}
assert Zeus.instance
def ex = shouldFail(RuntimeException) { new Zeus() }
assert ex.message ==
"Can't instantiate singleton Zeus. Use Zeus.instance"
© Rowell Belen
@DELEGATE
class NoisySet {
@Delegate
Set delegate = new HashSet()
@Override
boolean add(item) {
println "adding $item"
delegate.add(item)
}
}
def ns = new NoisySet()
ns.add(1)
ns.addAll([2, 3])
assert ns.size() == 3
© Rowell Belen
@MEMOIZED
@Memoized
Long fib(Integer n){
if (n < 2) {
return 1
}
return fib(n - 1) + fib(n - 2)
}
© Rowell Belen
@AUTOCLONE
@AutoClone
class Chef {
String name
List<String> recipes
}
def name = 'Gordon Ramsay'
def recipes = ['Snail porridge', 'Bacon & egg ice cream']
def c1 = new Chef(name: name, recipes: recipes)
def c2 = c1.clone()
assert c2.recipes == recipes
© Rowell Belen
"PIMP MY LIBRARY" PATTERN
© Rowell Belen
@CATEGORY - OVERRIDE
class Energy {
def usage(){ .. } // return joules
}
@Category(Energy)
class Therms {
def usage(){ .. } // override - return therms
}
use(Therms){
def energy = new Energy()
energy.usage() // returns usage in Therms
}
© Rowell Belen
@CATEGORY - ENHANCE
class Energy {
def usage(){ .. } // return joules
}
@Category(Energy)
class KilowattHour {
def kwUsage(){ .. } // enhance with new method - return usage in kWh
}
use(KilowattHour){
def energy = new Energy()
energy.usage() // returns in joules
energy.kwUsage() // returns in kWh
}
© Rowell Belen
WHAT ABOUT
CONCURRENCY?
© Rowell Belen
@WITHREADLOCK / @WITHWRITELOCK
class PhoneBook {
private final phoneNumbers = [:]
// multiple readers can access simultaneously
// unless lock is obtained by writer
@WithReadLock
def getNumber(key) {
phoneNumbers[key]
}
// readers will block until lock is released by the writer
@WithWriteLock
def addNumber(key, value) {
phoneNumbers[key] = value
}
}
© Rowell Belen
Concurrent Map/Filter/Reduce Example
import static groovyx.gpars.GParsPool.withPool
withPool {
def numbers = [1, 2, 3, 4, 5, 6]
assert [1, 4, 9] == numbers.parallel
.map { it * it }
.filter { it < 10 }
.collection
}
withPool {
assert 55 == [0, 1, 2, 3, 4].parallel
.map { it + 1 }
.map { it ** 2 }
.reduce { a, b -> a + b }
}
withPool(10) {...}
withPool(20, exceptionHandler) {...}
© Rowell Belen
Parallel Collections
withPool {
def numbers = [1, 2, 3, 4, 5, 6]
// dynamically enhanced with parallel processing capabilities
numbers.eachParallel{ .. }
numbers.eachWithIndexParallel{ .. }
numbers.collectParallel{ .. }
numbers.findAllParallel{ .. }
numbers.findAnyParallel{ .. }
numbers.findParallel{ .. }
numbers.everyParallel{ .. }
numbers.anyParallel{ .. }
numbers.grepParallel{ .. }
numbers.groupByParallel{ .. }
numbers.foldParallel{ .. }
numbers.minParallel{ .. }
numbers.maxParallel{ .. }
numbers.sumParallel{ .. }
numbers.splitParallel{ .. }
numbers.countParallel{ .. }
numbers.foldParallel{ .. }
}
© Rowell Belen
Implicit Task Coordination
def getDashboardData(req) {
def results = new Dataflows()
// These 3 tasks will execute in parallel
task {
results.user = fetchUserData(req)
}
task {
results.weather = fetchWeatherData(req)
}
task {
results.savings = fetchSavingsData(req)
}
// Blocks until results.user is bound
task {
results.devices = fetchDevices(req, results.user.defaultDevice)
}
results
}
© Rowell Belen
ERRRMAHHHHGERDD!!!
© Rowell Belen

More Related Content

Recently uploaded

Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
seospiralmantra
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 

Recently uploaded (20)

Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
MindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Cleaner and Leaner Groovy

  • 2. @BUILDER @Builder class Premise { def sqFeet def occupants def stories def heatingType def coolingType def homeType def yearBuilt } def premise = Premise.builder() .sqFeet(1200) .occupants(4) .stories(2) .heatingType('Furnace·(Gas)') .coolingType('Central·Air·Conditioning') .homeType('Single·Family·(detached)') .yearBuilt(1995).build() © Rowell Belen
  • 3. @TOSTRING @ToString(includeNames=true, ignoreNulls = true, excludes="ssn") class Customer { String first, last int age Collection favItems String ssn } def customer = new Customer(first:'Tom', last:'Jones', age:21, favItems:['Books', 'Games'], ssn:'xxx-xx-xxxxx') assert customer.toString() == 'Customer(first:Tom, last:Jones, age:21, favItems:[Books, Games])' © Rowell Belen
  • 4. @EQUALSANDHASHCODE @EqualsAndHashCode class Actor { String firstName, lastName } def magneto = new Actor(firstName:'Ian', lastName: 'McKellen') def gandalf = new Actor(firstName:'Ian', lastName: 'McKellen') assert magneto == gandalf © Rowell Belen
  • 5. @TUPLECONSTRUCTOR import groovy.transform.TupleConstructor @TupleConstructor class Athlete { String firstName, lastName } def a1 = new Athlete('Michael', 'Jordan') def a2 = new Athlete('Michael') assert a1.firstName == a2.firstName © Rowell Belen
  • 6. @LAZY class App { @Lazy AuthService authService = { ctx.getBean('AuthService.class') }() @Lazy // defer expensive initialization ApplicationContext ctx = { new AnnotationConfigApplicationContext(AppConfig.class) }() @Lazy UserService userService Profile getProfile(user){ authService.login(user) userService.findProfile(user) } } © Rowell Belen
  • 7. @IMMUTABLE @Immutable class User { String email Collection roles } def u = new User(email: 'email@host.com', roles: ['admin', 'user']) // Properties are readonly. shouldFail(ReadOnlyPropertyException) { u.email = 'new@email.com' } // Collections are also wrapped in immutable wrapper classes shouldFail(UnsupportedOperationException) { u.roles << 'new role' } © Rowell Belen
  • 8. @SINGLETON @Singleton class Zeus { ... } assert Zeus.instance def ex = shouldFail(RuntimeException) { new Zeus() } assert ex.message == "Can't instantiate singleton Zeus. Use Zeus.instance" © Rowell Belen
  • 9. @DELEGATE class NoisySet { @Delegate Set delegate = new HashSet() @Override boolean add(item) { println "adding $item" delegate.add(item) } } def ns = new NoisySet() ns.add(1) ns.addAll([2, 3]) assert ns.size() == 3 © Rowell Belen
  • 10. @MEMOIZED @Memoized Long fib(Integer n){ if (n < 2) { return 1 } return fib(n - 1) + fib(n - 2) } © Rowell Belen
  • 11. @AUTOCLONE @AutoClone class Chef { String name List<String> recipes } def name = 'Gordon Ramsay' def recipes = ['Snail porridge', 'Bacon & egg ice cream'] def c1 = new Chef(name: name, recipes: recipes) def c2 = c1.clone() assert c2.recipes == recipes © Rowell Belen
  • 12. "PIMP MY LIBRARY" PATTERN © Rowell Belen
  • 13. @CATEGORY - OVERRIDE class Energy { def usage(){ .. } // return joules } @Category(Energy) class Therms { def usage(){ .. } // override - return therms } use(Therms){ def energy = new Energy() energy.usage() // returns usage in Therms } © Rowell Belen
  • 14. @CATEGORY - ENHANCE class Energy { def usage(){ .. } // return joules } @Category(Energy) class KilowattHour { def kwUsage(){ .. } // enhance with new method - return usage in kWh } use(KilowattHour){ def energy = new Energy() energy.usage() // returns in joules energy.kwUsage() // returns in kWh } © Rowell Belen
  • 16. @WITHREADLOCK / @WITHWRITELOCK class PhoneBook { private final phoneNumbers = [:] // multiple readers can access simultaneously // unless lock is obtained by writer @WithReadLock def getNumber(key) { phoneNumbers[key] } // readers will block until lock is released by the writer @WithWriteLock def addNumber(key, value) { phoneNumbers[key] = value } } © Rowell Belen
  • 17. Concurrent Map/Filter/Reduce Example import static groovyx.gpars.GParsPool.withPool withPool { def numbers = [1, 2, 3, 4, 5, 6] assert [1, 4, 9] == numbers.parallel .map { it * it } .filter { it < 10 } .collection } withPool { assert 55 == [0, 1, 2, 3, 4].parallel .map { it + 1 } .map { it ** 2 } .reduce { a, b -> a + b } } withPool(10) {...} withPool(20, exceptionHandler) {...} © Rowell Belen
  • 18. Parallel Collections withPool { def numbers = [1, 2, 3, 4, 5, 6] // dynamically enhanced with parallel processing capabilities numbers.eachParallel{ .. } numbers.eachWithIndexParallel{ .. } numbers.collectParallel{ .. } numbers.findAllParallel{ .. } numbers.findAnyParallel{ .. } numbers.findParallel{ .. } numbers.everyParallel{ .. } numbers.anyParallel{ .. } numbers.grepParallel{ .. } numbers.groupByParallel{ .. } numbers.foldParallel{ .. } numbers.minParallel{ .. } numbers.maxParallel{ .. } numbers.sumParallel{ .. } numbers.splitParallel{ .. } numbers.countParallel{ .. } numbers.foldParallel{ .. } } © Rowell Belen
  • 19. Implicit Task Coordination def getDashboardData(req) { def results = new Dataflows() // These 3 tasks will execute in parallel task { results.user = fetchUserData(req) } task { results.weather = fetchWeatherData(req) } task { results.savings = fetchSavingsData(req) } // Blocks until results.user is bound task { results.devices = fetchDevices(req, results.user.defaultDevice) } results } © Rowell Belen