DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Groovy Goodness: Chaining Traits

Groovy Goodness: Chaining Traits

Hubert Klein Ikkink user avatar by
Hubert Klein Ikkink
·
May. 24, 14 · Java Zone · Interview
Like (0)
Save
Tweet
3.85K Views

Join the DZone community and get the full member experience.

Join For Free

Since Groovy 2.3 we can use traits in our code. We can even chain traits using the so called stackable traits feature. This means a trait can delegate to another trait or we can stop the delegation base based on a condition. Inside the method implementation of a trait we can use super.method to delegate to the next trait (if available) in the chain. If we don't use super.method the chain is stopped.

In the following sample code we want to transform a String input value to an output value. We implement the transform method from theTransformer interface using different traits. For example the Upper trait will make the input value upper cased and invokes super.transform to delegate to the next trait. Then we write new classes that implement the traits. The order of the traits determines the chain. The last declared trait is invoked first then the traits defined from right to left are invoked.

/** 
 * Simple interface with one method to 
 * transform a String value.
 */
interface Transformer {
    String transform(String input)
}

/** Default trait will return the input value unchanged. */
trait DefaultTransformer implements Transformer {
    String transform(String input) {
        input
    }
}

/** Transform the String value to upper case */
trait Upper implements Transformer {
    String transform(String input) {
        super.transform(input.toUpperCase())
    }
}

/** Remove 'mr' from input String value. */
trait Filter implements Transformer {
    String transform(String input) {
        super.transform(input - 'mr')
    }
}

/**
 * Simple class uses three traits. The value property get method
 * returns the transformed value.
 */
class StringTransformer implements DefaultTransformer, Upper, Filter {
    String value
    String getValue() { transform(value) }
}

// Create StringTransformer instance.
def transformer = new StringTransformer(value: 'mrhaki')

assert transformer.value == 'HAKI' 


// Use same traits, but in different order.
class OtherStringTransformer implements DefaultTransformer, Filter, Upper {
    String value
    String getValue() { transform(value) }
}

// Create OtherStringTransformer instance.
def otherTransformer = new OtherStringTransformer(value: 'mrhaki')

// The Filter trait cannot find 'mr', 
// because the String value is already in
// upper case after the Upper trait.
assert otherTransformer.value == 'MRHAKI'


/** Only chain input values smaller than 5 characters. */
trait SmallFilter implements Transformer {
    String transform(String input) {
        if (input.size() < 5) {
            super.transform(input)
        } else {
            ''
        }
    }
}

class SmallStringTransformer implements DefaultTransformer, Upper, SmallFilter {
    String value
    String getValue() { transform(value) }
}

def smallTransformer = new SmallStringTransformer(value: 'mrhaki')
assert smallTransformer.value == ''

smallTransformer.value = 'haki'
assert smallTransformer.value == 'HAKI'

Code written with Groovy 2.3.1.

Trait (computer programming) Groovy (programming language)

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Generate Fake Test Data
  • Don't Underestimate Documentation
  • 6 Things Startups Can Do to Avoid Tech Debt
  • Password Authentication. How to Correctly Do It.

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo