10. A DSL is just another tool in our toolbox. Itâs a jig to help us build our applications. picture copyrighted @2007 Pat Warner, http://www.patwarner.com
24. class MyGroovy extends GroovyClassLoader { protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource source) { CompilationUnit cu = super .createCompilationUnit(config, source); cu.addPhaseOperation( new PrimaryClassNodeOperation() { public void call (SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { String name = classNode.getName(); if (name.endsWith( "Foo" )) { BlockStatement code = new BlockStatement(); classNode.addMethod( âbar" ,Opcodes.ACC_PUBLIC, null , null , null ,code); } } },Phases.CONVERSION); return cu; } } Adapted from blackdragâs blog: http://blackdragsview.blogspot.com/2006/11/chitchat-with-groovy-compiler.html
25. Meta Object Protocol - Determines whatâs running at Runtime - add/modify/intercept methods, properties MetaClass Class getFoo() doesntExistOnClass() Other Code
27. Duck typing : flexible code if it walks like a duck⊠and it quacks like a duck⊠its probably a âŠ. a = âa string" println a. class // => class java.lang.String a = 1 println a. class // => class java.lang.Integer
29. Using â use â (Groovy Categories) class MeasureCategory { static Measurement getLbs( final Integer self) { new Measurement(self, Measurement.Pounds) } } aClosure = {-> println 4 .lbs.of( "Sugar" ) } use (MeasureCategory. class ) { println 1 .lbs.of( "Carrots" ) // -> 1 Pounds of Carrots aClosure. call () // -> 4 Pounds of Sugar }
30. Using ExpandoMetaClass: metaClass = new ExpandoMetaClass(Integer. class , true ) metaClass.getLbs << {-> "${delegate} pounds" } metaClass.initialize() i = 1 ; println i // => 1 println i. class // => java.lang.Integer println i.lbs // => 1 pounds
31. Using ExpandoMetaClass: metaClass = new ExpandoMetaClass(Integer. class , true ) metaClass.getLbs << {-> "${delegate} pounds" } metaClass.initialize() i = 1 ; println i // => 1 println i. class // => java.lang.Integer println i.lbs // => 1 pounds
32. To Expando or not to Expando ⊠- global usage (good and bad) - must be aware of context - naming collisions use + aspects/annotations = somewhat finer grained control
33. Operator Overloading: class Foo { String meh; public Foo(String meh) { this .meh = meh} public String toString() { meh } public Foo plus (other) { new Foo( this .meh + other.toString()) } } a = new Foo( "Hello " ) b = new Foo( "World" ) c = "New World" println a + b // -> âHello Worldâ println a + c // -> âHello New Worldâ