SlideShare a Scribd company logo
Designing with
Groovy Traits
Naresha K
Chief Technologist
Channel Bridge Software Labs
naresha.k@gmail.com
@naresha_k
About Me
OOP
Object Oriented Maturity Model
0
1
2
Designing with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf India
I made up the term
‘object-oriented',
and I can tell you
I didn't have that in mind
Alan Kay
iskov Substitution Principle
"Favour 'object composition'
over
'class inheritance'."
Designing with Groovy Traits - Gr8Conf India
A case for
Traits
The Problem
Bird charlie = new Bird()
charlie.fly()
Butterfly aButterFly = new Butterfly()
aButterFly.fly()
Recall Interfaces
interface Flyable {
def fly()
}
class Bird implements Flyable {
def fly() {
println "Flying..."
}
}
class Butterfly implements Flyable {
def fly() {
println "Flying..."
}
}
The Smell
class Bird implements Flyable {
def fly() {
println "Flying..."
}
}
class Butterfly implements Flyable {
def fly() {
println "Flying..."
}
}
DRY
class FlyableImpl implements Flyable {
def fly() {
println 'Flying...'
}
}
class Bird implements Flyable {
def fly() {
new FlyableImpl().fly()
}
}
Making it Groovier
class DefaultFlyable implements Flyable {
def fly() {
println 'Flying...'
}
}
class Bird {
@Delegate
Flyable flyable = new DefaultFlyable()
}
Summarizing
interface Flyable {
def fly()
}
class DefaultFlyable implements Flyable {
def fly() {
println 'Flying...'
}
}
class Bird {
@Delegate
Flyable flyable = new DefaultFlyable()
}
Introducing Trait
trait Flyable {
def fly() {
println "Flying.."
}
}
class Bird implements Flyable {}
Multiple Capabilities
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()
The Mechanics
Overriding Methods from a Trait
trait Speaker {
def speak() {
println "speaking"
}
}
class Gr8ConfSpeaker implements Speaker {
def speak() {
println "Groovy is Groovy!"
}
}
new Gr8ConfSpeaker().speak()
Traits can implement interfaces
interface Programmer {
def code()
}
trait GroovyProgrammer implements Programmer {
def code() {
println 'coding Groovy'
}
}
class Engineer implements GroovyProgrammer {}
new Engineer().code()
Traits can declare abstract methods
trait Programmer {
abstract String getLanguage()
def code() {
println "Coding ${getLanguage()}"
}
}
class GroovyProgrammer implements Programmer {
String getLanguage() { "Groovy"}
}
new GroovyProgrammer().code()
Traits can have a state
trait Programmer {
String language
def code() {
println "Coding ${language}"
}
}
class GroovyProgrammer implements Programmer {}
new GroovyProgrammer(language: 'Groovy').code()
A trait can extend another trait
trait JavaProgrammer {
def codeObjectOriented() {
println 'Coding OOP'
}
}
trait GroovyProgrammer extends JavaProgrammer {
def codeFunctional() {
println 'Coding FP'
}
}
class Engineer implements GroovyProgrammer {}
Engineer raj = new Engineer()
raj.codeFunctional()
raj.codeObjectOriented()
A trait can extend from multiple traits
trait Reader {
def read() { println 'Reading'}
}
trait Evaluator {
def eval() { println 'Evaluating'}
}
trait Printer {
def printer() { println 'Printing'}
}
trait Repl implements Reader, Evaluator, Printer {
}
The diamond problem
trait GroovyProgrammer {
def learn() { println 'Learning Traits'}
}
trait JavaProgrammer {
def learn() { println 'Busy coding'}
}
class Dev implements JavaProgrammer,
GroovyProgrammer {}
new Dev().learn()
Finer control on the diamond problem
class Dev implements JavaProgrammer,
GroovyProgrammer {
def learn() {
JavaProgrammer.super.learn()
}
}
Applying traits at run time
trait Flyable{
def fly(){
println "Flying.."
}
}
class Person {}
new Person().fly()
Applying traits at run time
def boardAPlane(Person person) {
person.withTraits Flyable
}
def passenger = boardAPlane(new Person())
passenger.fly()
More examples
Composing Behaviours
trait UserContextAware {
UserContext getUserContext(){
// implementation
}
}
class ProductApi implements UserContextAware {}
class PriceApi implements UserContextAware {}
common fields
trait Auditable {
String createdBy
String modifiedBy
Date dateCreated
Date lastUpdated
}
class Price implements Auditable {
String productCode
BigDecimal mrp
BigDecimal sellingPrice
}
common fields - a trait approach
Price groovyInActionToday = new Price(
productCode: '9789351198260',
mrp: 899,
sellingPrice: 751,
createdBy: 'admin',
modifiedBy: 'rk'
)
println groovyInActionToday.createdBy
println groovyInActionToday.modifiedBy
Chaining
interface Manager {
def approve(BigDecimal amount)
}
Chaining
trait JuniorManager implements Manager {
def approve(BigDecimal amount){
if(amount < 10000G){ println "Approved by JM” }
else{
println "Sending to SM"
super.approve()
}
}
}
trait SeniorManager implements Manager {
def approve(BigDecimal amount){
println "Approved by SM"
}
}
Chaining
class FinanceDepartment implements SeniorManager,
JuniorManager {}
FinanceDepartment finance = new FinanceDepartment()
finance.approve(3000)
finance.approve(30000)
Groovy Coding!

More Related Content

PDF
Discovering functional treasure in idiomatic Groovy
PDF
Polyglot JVM
PDF
Functional Programming with Groovy
PPT
Polyglot Programming in the JVM
PDF
Ruby 程式語言簡介
PPTX
Groovy!
PDF
tictactoe groovy
KEY
Polyglot Grails
Discovering functional treasure in idiomatic Groovy
Polyglot JVM
Functional Programming with Groovy
Polyglot Programming in the JVM
Ruby 程式語言簡介
Groovy!
tictactoe groovy
Polyglot Grails

What's hot (20)

ODP
AST Transformations at JFokus
PPT
Groovy for Java Developers
PDF
Groovy for java developers
KEY
groovy & grails - lecture 3
KEY
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
PDF
GraphQL API in Clojure
PDF
re-frame à la spec
ODP
Groovy Ast Transformations (greach)
KEY
PHPSpec BDD for PHP
PDF
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
PDF
C++ for Java Developers (JavaZone Academy 2018)
KEY
Mirah Talk for Boulder Ruby Group
PDF
Diving into HHVM Extensions (PHPNW Conference 2015)
PDF
Grooscript gr8conf
PDF
Natural Language Toolkit (NLTK), Basics
PDF
Lift off with Groovy 2 at JavaOne 2013
PPTX
C# 7.0 Hacks and Features
PDF
Go 1.10 Release Party - PDX Go
PDF
"Simple Made Easy" Made Easy
PPTX
Building High Performance Web Applications and Sites
AST Transformations at JFokus
Groovy for Java Developers
Groovy for java developers
groovy & grails - lecture 3
Groovy DSLs, from Beginner to Expert - Guillaume Laforge and Paul King - Spri...
GraphQL API in Clojure
re-frame à la spec
Groovy Ast Transformations (greach)
PHPSpec BDD for PHP
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
C++ for Java Developers (JavaZone Academy 2018)
Mirah Talk for Boulder Ruby Group
Diving into HHVM Extensions (PHPNW Conference 2015)
Grooscript gr8conf
Natural Language Toolkit (NLTK), Basics
Lift off with Groovy 2 at JavaOne 2013
C# 7.0 Hacks and Features
Go 1.10 Release Party - PDX Go
"Simple Made Easy" Made Easy
Building High Performance Web Applications and Sites
Ad

Viewers also liked (13)

PDF
science 8
PDF
G30022_Karen Devine_DL_Print
PDF
PPTX
Trabajo final
DOCX
ARC FLASH MITIGATION USING ACTIVE HIGH-SPEED SWITCHING
PDF
Biostatistics Workshop: Regression
PDF
Comandos usados en kali linux
PDF
Overview of JSI & USAID | DELIVER PROJECT Reproductive Health Supplies Monito...
PPTX
Georgia txostena
PPTX
Kamal final presentation eee reb- comilla
PDF
Karen Devine Ind NUI Seanad Proposals
DOC
ANKIT RASUMA
science 8
G30022_Karen Devine_DL_Print
Trabajo final
ARC FLASH MITIGATION USING ACTIVE HIGH-SPEED SWITCHING
Biostatistics Workshop: Regression
Comandos usados en kali linux
Overview of JSI & USAID | DELIVER PROJECT Reproductive Health Supplies Monito...
Georgia txostena
Kamal final presentation eee reb- comilla
Karen Devine Ind NUI Seanad Proposals
ANKIT RASUMA
Ad

Similar to Designing with Groovy Traits - Gr8Conf India (20)

PPT
Traits in scala
PPT
Traits inscala
PDF
Inheritance And Traits
ODP
1.6 oo traits
PDF
TI1220 Lecture 8: Traits & Type Parameterization
KEY
Traits composition
DOCX
Using traits in PHP
ODT
Trait blog
PPT
Traits: A New Language Feature for PHP?
PDF
Stateful traits in Pharo
PDF
Favouring Composition - The Groovy Way
PPT
Scala idioms
PDF
Scala traits
PPTX
Php traits
PPT
Introduction to Scala for Data Science Technology
PPTX
Expression Problem in Scala
PPTX
Qcon2011 functions rockpresentation_scala
PDF
Scala in practice - 3 years later
PDF
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...
Traits in scala
Traits inscala
Inheritance And Traits
1.6 oo traits
TI1220 Lecture 8: Traits & Type Parameterization
Traits composition
Using traits in PHP
Trait blog
Traits: A New Language Feature for PHP?
Stateful traits in Pharo
Favouring Composition - The Groovy Way
Scala idioms
Scala traits
Php traits
Introduction to Scala for Data Science Technology
Expression Problem in Scala
Qcon2011 functions rockpresentation_scala
Scala in practice - 3 years later
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...

More from Naresha K (20)

PDF
The Groovy Way of Testing with Spock
PDF
Evolving with Java - How to Remain Effective
PDF
Take Control of your Integration Testing with TestContainers
PDF
Implementing Resilience with Micronaut
PDF
Take Control of your Integration Testing with TestContainers
PDF
Effective Java with Groovy - How Language Influences Adoption of Good Practices
PDF
What's in Groovy for Functional Programming
PDF
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
PDF
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
PDF
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
PDF
Implementing Cloud-Native Architectural Patterns with Micronaut
PDF
Groovy - Why and Where?
PDF
Leveraging Micronaut on AWS Lambda
PDF
Groovy Refactoring Patterns
PDF
Implementing Cloud-native Architectural Patterns with Micronaut
PDF
Effective Java with Groovy
PDF
Evolving with Java - How to remain Relevant and Effective
PDF
Effective Java with Groovy - How Language can Influence Good Practices
PDF
Beyond Lambdas & Streams - Functional Fluency in Java
PDF
GORM - The polyglot data access toolkit
The Groovy Way of Testing with Spock
Evolving with Java - How to Remain Effective
Take Control of your Integration Testing with TestContainers
Implementing Resilience with Micronaut
Take Control of your Integration Testing with TestContainers
Effective Java with Groovy - How Language Influences Adoption of Good Practices
What's in Groovy for Functional Programming
Effective Java with Groovy & Kotlin - How Languages Influence Adoption of Goo...
Effective Java with Groovy & Kotlin How Languages Influence Adoption of Good ...
Eclipse Collections, Java Streams & Vavr - What's in them for Functional Pro...
Implementing Cloud-Native Architectural Patterns with Micronaut
Groovy - Why and Where?
Leveraging Micronaut on AWS Lambda
Groovy Refactoring Patterns
Implementing Cloud-native Architectural Patterns with Micronaut
Effective Java with Groovy
Evolving with Java - How to remain Relevant and Effective
Effective Java with Groovy - How Language can Influence Good Practices
Beyond Lambdas & Streams - Functional Fluency in Java
GORM - The polyglot data access toolkit

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
project resource management chapter-09.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
OMC Textile Division Presentation 2021.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Approach and Philosophy of On baking technology
Encapsulation_ Review paper, used for researhc scholars
A novel scalable deep ensemble learning framework for big data classification...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Heart disease approach using modified random forest and particle swarm optimi...
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Programs and apps: productivity, graphics, security and other tools
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
project resource management chapter-09.pdf
Hindi spoken digit analysis for native and non-native speakers
Univ-Connecticut-ChatGPT-Presentaion.pdf
DP Operators-handbook-extract for the Mautical Institute
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
1 - Historical Antecedents, Social Consideration.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A comparative analysis of optical character recognition models for extracting...
OMC Textile Division Presentation 2021.pptx

Designing with Groovy Traits - Gr8Conf India

  • 1. Designing with Groovy Traits Naresha K Chief Technologist Channel Bridge Software Labs naresha.k@gmail.com @naresha_k
  • 3. OOP
  • 8. I made up the term ‘object-oriented', and I can tell you I didn't have that in mind Alan Kay
  • 13. The Problem Bird charlie = new Bird() charlie.fly() Butterfly aButterFly = new Butterfly() aButterFly.fly()
  • 15. class Bird implements Flyable { def fly() { println "Flying..." } } class Butterfly implements Flyable { def fly() { println "Flying..." } }
  • 16. The Smell class Bird implements Flyable { def fly() { println "Flying..." } } class Butterfly implements Flyable { def fly() { println "Flying..." } }
  • 17. DRY class FlyableImpl implements Flyable { def fly() { println 'Flying...' } } class Bird implements Flyable { def fly() { new FlyableImpl().fly() } }
  • 18. Making it Groovier class DefaultFlyable implements Flyable { def fly() { println 'Flying...' } } class Bird { @Delegate Flyable flyable = new DefaultFlyable() }
  • 19. Summarizing interface Flyable { def fly() } class DefaultFlyable implements Flyable { def fly() { println 'Flying...' } } class Bird { @Delegate Flyable flyable = new DefaultFlyable() }
  • 20. Introducing Trait trait Flyable { def fly() { println "Flying.." } } class Bird implements Flyable {}
  • 21. Multiple Capabilities 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()
  • 23. Overriding Methods from a Trait trait Speaker { def speak() { println "speaking" } } class Gr8ConfSpeaker implements Speaker { def speak() { println "Groovy is Groovy!" } } new Gr8ConfSpeaker().speak()
  • 24. Traits can implement interfaces interface Programmer { def code() } trait GroovyProgrammer implements Programmer { def code() { println 'coding Groovy' } } class Engineer implements GroovyProgrammer {} new Engineer().code()
  • 25. Traits can declare abstract methods trait Programmer { abstract String getLanguage() def code() { println "Coding ${getLanguage()}" } } class GroovyProgrammer implements Programmer { String getLanguage() { "Groovy"} } new GroovyProgrammer().code()
  • 26. Traits can have a state trait Programmer { String language def code() { println "Coding ${language}" } } class GroovyProgrammer implements Programmer {} new GroovyProgrammer(language: 'Groovy').code()
  • 27. A trait can extend another trait trait JavaProgrammer { def codeObjectOriented() { println 'Coding OOP' } } trait GroovyProgrammer extends JavaProgrammer { def codeFunctional() { println 'Coding FP' } } class Engineer implements GroovyProgrammer {} Engineer raj = new Engineer() raj.codeFunctional() raj.codeObjectOriented()
  • 28. A trait can extend from multiple traits trait Reader { def read() { println 'Reading'} } trait Evaluator { def eval() { println 'Evaluating'} } trait Printer { def printer() { println 'Printing'} } trait Repl implements Reader, Evaluator, Printer { }
  • 29. The diamond problem trait GroovyProgrammer { def learn() { println 'Learning Traits'} } trait JavaProgrammer { def learn() { println 'Busy coding'} } class Dev implements JavaProgrammer, GroovyProgrammer {} new Dev().learn()
  • 30. Finer control on the diamond problem class Dev implements JavaProgrammer, GroovyProgrammer { def learn() { JavaProgrammer.super.learn() } }
  • 31. Applying traits at run time trait Flyable{ def fly(){ println "Flying.." } } class Person {} new Person().fly()
  • 32. Applying traits at run time def boardAPlane(Person person) { person.withTraits Flyable } def passenger = boardAPlane(new Person()) passenger.fly()
  • 34. Composing Behaviours trait UserContextAware { UserContext getUserContext(){ // implementation } } class ProductApi implements UserContextAware {} class PriceApi implements UserContextAware {}
  • 35. common fields trait Auditable { String createdBy String modifiedBy Date dateCreated Date lastUpdated } class Price implements Auditable { String productCode BigDecimal mrp BigDecimal sellingPrice }
  • 36. common fields - a trait approach Price groovyInActionToday = new Price( productCode: '9789351198260', mrp: 899, sellingPrice: 751, createdBy: 'admin', modifiedBy: 'rk' ) println groovyInActionToday.createdBy println groovyInActionToday.modifiedBy
  • 37. Chaining interface Manager { def approve(BigDecimal amount) }
  • 38. Chaining trait JuniorManager implements Manager { def approve(BigDecimal amount){ if(amount < 10000G){ println "Approved by JM” } else{ println "Sending to SM" super.approve() } } } trait SeniorManager implements Manager { def approve(BigDecimal amount){ println "Approved by SM" } }
  • 39. Chaining class FinanceDepartment implements SeniorManager, JuniorManager {} FinanceDepartment finance = new FinanceDepartment() finance.approve(3000) finance.approve(30000)