SlideShare a Scribd company logo
DSL로 만나는 Groovy
장시영
KGGUG
DSL
•DSLR? DSL?
A domain-specific language (DSL) is a computer language specialized to a
particular application domain.
http://en.wikipedia.org/wiki/Domain-specific_language
http://www.aladin.co.kr/shop/wproduct.aspx?ISBN=8991268994

•DSL <-> GPL(General Purpose Language)
•DSL = Mini Languages
•DSL Example => XML, HTML, CSS, SQL
•Groovy로 해석되는 DSL
– 각종 Builder, GORM, gradle, Grails
Groovy?
•
•
•
•

Ruby?
Dynamic Language?
다양한 빌더
Grails, gradle, GORM 등
Groovy Builder DSL – XML
writer = new StringWriter()
builder = new groovy.xml.MarkupBuilder(writer)
builder.numbers {
description 'Squares and factors of 10..15'
for (i in 10..15) {
number (value: i, square: i*i) {
//#1
for ( j in 2..<i) {
if (i % j == 0) {
factor (value: j) //#2
}
}
}
}
}
println writer
http://groovyconsole.appspot.com/
Groovy Builder DSL - HTML
def writer = new StringWriter()
def html = new groovy.xml.MarkupBuilder(writer)
html.html {
head { title 'Constructed by MarkupBuilder' }
body {
h1 'What can I do with MarkupBuilder?'
form (action:'whatever') {
for (line in [
'Produce HTML',
'Produce XML',
'Have some fun'
]){
input(type:'checkbox',checked:'checked', id:line, '')
label(for:line, line)
br('')
}
}
}
}
println writer
GORM – DSL
• ORM DSL

– Mapping

• Table, Column mapping
• Relational mapping

– ORM관련 설정
•
•
•
•

Cache 전략
Custom ID 전략
Composite Primary Keys
Index 설정

– http://grails.org/doc/latest/guide/single.html#ormdsl

• Query DSL
–

Basic Query

• list, get, getAll

– Dynamic Finders
• findByXXX
–
–

Book.findByTitle(„정글만리‟), findByTitleLike(„%정글‟)
http://grails.org/doc/latest/ref/Domain%20Classes/findBy.html
Groovy로 만든 한글 DSL
Object.metaClass.을 =
Object.metaClass.를 =
Object.metaClass.의 =
{ clos -> clos(delegate) }
먼저 = { it }
표시하라 = { println it }
제곱근 = { Math.sqrt(it) }
먼저 100 의 제곱근 을 표시하라
먼저(100).의(제곱근).을(표시하라)
출처: http://it.gilbird.com/textyle/8318
Groovy는 왜 DSL에 강한가?
• Dynamic Language

– Dynamic Type
num = 10; str = “20”
assert num instanceof Integer
assert str instanceof String
– Closure
• Caller에게 양보하기
– MOP(Meta Class, Expando Class)
• 요술상자, 아메바
– Groovy‟s chain method calls (GEP 3)
• 괄호 빼기
먼저 100 의 제곱근 을 표시하라
먼저(100).의(제곱근).을(표시하라)

•

JVM 기반

– Groovy는 결국 Java Class로 컴파일
– 거의 95%이상 Java와 동일하게 코딩 가능
– Java와 Groovy의 혼용
Groovy MOP
• MOP(Meta Object Protocol)
– MetaObjectProtocol
• http://en.wikipedia.org/wiki/Metaobject
• MetaClass, ExpandoMetaClass
http://mrhaki.blogspot.kr/2009/10/groovy-goodness-expando-as-dynamic-bean.html

– 요술을 부리는 MOP Hooks
• invokeMethod, methodMissing, get/setProperty,
propertyMissing
Groovy MetaClass
MOP Hooks - invokeMethod
import org.codehaus.groovy.runtime.StringBufferWriter
import org.codehaus.groovy.runtime.InvokerHelper
class Traceable implements GroovyInterceptable {
Writer writer = new PrintWriter(System.out)
private int indent = 0
Object invokeMethod(String name, Object args){
writer.write("n" + ' '*indent + "before method '$name'")
writer.flush()
indent++
def metaClass = InvokerHelper.getMetaClass(this)
def result = metaClass.invokeMethod(this, name, args)
indent-writer.write("n" + ' '*indent + "after method '$name'")
writer.flush()
return result
}
}
class Whatever extends Traceable {
int outer(){
return inner()
}
int inner(){
return 1
}
}
def log = new StringBuffer()
def traceMe = new Whatever(writer: new StringBufferWriter(log))
assert 1 == traceMe.outer()
println log
Method 실행 순서
MOP Hooks – methodMissing
class GORM {

}

def dynamicMethods = [...] // an array of dynamic methods that use regex
def methodMissing(String name, args) {
def method = dynamicMethods.find { it.match(name) }
if(method) {
GORM.metaClass."$name" = { Object[] varArgs ->
method.invoke(delegate, name, varArgs)
}
return method.invoke(delegate,name, args)
}
else throw new MissingMethodException(name, delegate, args)
}

http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing
Groovy Closure
def lineFile = new File(getClass().getResource("numbers.txt").getPath())
def sumValue = 0, multiflyValue = 1, concateValue = ''
lineFile.eachLine {
sumValue += Integer.parseInt(it)
multiflyValue *= Integer.parseInt(it)
concateValue += it
}
assert sumValue == 10
assert multiflyValue == 24
assert concateValue == '1234'
한국어 DSL로 돌아와서
Object.metaClass.을 =
Object.metaClass.를 =
Object.metaClass.의 =
{ clos -> clos(delegate) }
먼저 = { it }
표시하라 = { println it }
제곱근 = { Math.sqrt(it) }
먼저 100 의 제곱근 을 표시하라
먼저(100).의(제곱근).을(표시하라)
100.제곱근 을 표시하라
출처: http://it.gilbird.com/textyle/8318
관련 자료
• http://notes.3kbo.com/groovy-dsls
• http://en.wikipedia.org/wiki/Domainspecific_language
• DSL 번역본
• 프로그래밍 그루비
• 한국어 DSL
• Groovy for Domain-Specific Languages
• http://en.wikipedia.org/wiki/Metaobject
• http://groovy.codehaus.org/api/overviewsummary.html
• Groovy Grails 의 좋은 점
• ★ Groovy

More Related Content

PDF
Groovy Finesse
KEY
Groovy overview, DSLs and ecosystem - Mars JUG - 2010
PDF
Understanding how concurrency work in os
PDF
Why don't you Groovy?
PDF
Venkat Subramaniam Blending Java With Dynamic Languages
PDF
Buildr - build like you code
PPTX
WeCode IL: Confessions of a java developer that fell in love with the groovy...
PDF
Groovy and noteworthy
Groovy Finesse
Groovy overview, DSLs and ecosystem - Mars JUG - 2010
Understanding how concurrency work in os
Why don't you Groovy?
Venkat Subramaniam Blending Java With Dynamic Languages
Buildr - build like you code
WeCode IL: Confessions of a java developer that fell in love with the groovy...
Groovy and noteworthy

What's hot (20)

PDF
Venkat Subramaniam Building DSLs In Groovy
PPTX
PDF
JavaCro 2016 - From Java to Groovy: Adventure Time!
PDF
Pluggable web app using Angular (Odessa JS conf)
PPTX
Exploring Ruby on Rails and PostgreSQL
PPTX
Web Development: Making it the right way
PDF
Quick Review of Desktop and Native Apps using Javascript
PDF
Introduction to TypeScript
PDF
Intro to Crystal Programming Language
PPTX
Introduction to go lang
PPSX
Webpack & EcmaScript 6 (Webelement #32)
PDF
Scala vs ruby
PDF
Kotlin introduction
PDF
Crystal
PDF
Use groovy & grails in your spring boot projects
PDF
Gluecon 2014 - Bringing Node.js to the JVM
PPTX
The Saga of JavaScript and TypeScript: Part 1
PPTX
Php[tek] 2016 - BDD with Behat for Beginners
PDF
There is something about JavaScript - Choose Forum 2014
PPTX
Desarrollo multiplataforma con kotlin | UPV 2018
Venkat Subramaniam Building DSLs In Groovy
JavaCro 2016 - From Java to Groovy: Adventure Time!
Pluggable web app using Angular (Odessa JS conf)
Exploring Ruby on Rails and PostgreSQL
Web Development: Making it the right way
Quick Review of Desktop and Native Apps using Javascript
Introduction to TypeScript
Intro to Crystal Programming Language
Introduction to go lang
Webpack & EcmaScript 6 (Webelement #32)
Scala vs ruby
Kotlin introduction
Crystal
Use groovy & grails in your spring boot projects
Gluecon 2014 - Bringing Node.js to the JVM
The Saga of JavaScript and TypeScript: Part 1
Php[tek] 2016 - BDD with Behat for Beginners
There is something about JavaScript - Choose Forum 2014
Desarrollo multiplataforma con kotlin | UPV 2018
Ad

Viewers also liked (8)

PDF
GKAC 2014 Nov. - 그루비로 안드로이드 앱 개발하기
ODP
무식하게 배우는 gradle
PDF
Creating Domain Specific Languages in Python
PPTX
서유럽 여행기 0820
DOCX
Apache 핵심 프로젝트 camel 엿보기
PDF
gradle로 안드로이드 앱 빌드하기
PDF
알파희 - PyPy/RPython으로 20배 빨라지는 아희 JIT 인터프리터
PDF
AWS로 사용자 천만명 서비스 만들기 - 윤석찬 (AWS 테크에반젤리스트) :: AWS 웨비나 시리즈 2015
GKAC 2014 Nov. - 그루비로 안드로이드 앱 개발하기
무식하게 배우는 gradle
Creating Domain Specific Languages in Python
서유럽 여행기 0820
Apache 핵심 프로젝트 camel 엿보기
gradle로 안드로이드 앱 빌드하기
알파희 - PyPy/RPython으로 20배 빨라지는 아희 JIT 인터프리터
AWS로 사용자 천만명 서비스 만들기 - 윤석찬 (AWS 테크에반젤리스트) :: AWS 웨비나 시리즈 2015
Ad

Recently uploaded (20)

PDF
August Patch Tuesday
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mushroom cultivation and it's methods.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Getting Started with Data Integration: FME Form 101
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Machine Learning_overview_presentation.pptx
PDF
A comparative study of natural language inference in Swahili using monolingua...
August Patch Tuesday
MIND Revenue Release Quarter 2 2025 Press Release
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Tartificialntelligence_presentation.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Univ-Connecticut-ChatGPT-Presentaion.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Assigned Numbers - 2025 - Bluetooth® Document
Unlocking AI with Model Context Protocol (MCP)
Mushroom cultivation and it's methods.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Getting Started with Data Integration: FME Form 101
Group 1 Presentation -Planning and Decision Making .pptx
A comparative analysis of optical character recognition models for extracting...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
1. Introduction to Computer Programming.pptx
Machine learning based COVID-19 study performance prediction
Machine Learning_overview_presentation.pptx
A comparative study of natural language inference in Swahili using monolingua...

Dsl로 만나는 groovy

  • 2. DSL •DSLR? DSL? A domain-specific language (DSL) is a computer language specialized to a particular application domain. http://en.wikipedia.org/wiki/Domain-specific_language http://www.aladin.co.kr/shop/wproduct.aspx?ISBN=8991268994 •DSL <-> GPL(General Purpose Language) •DSL = Mini Languages •DSL Example => XML, HTML, CSS, SQL •Groovy로 해석되는 DSL – 각종 Builder, GORM, gradle, Grails
  • 4. Groovy Builder DSL – XML writer = new StringWriter() builder = new groovy.xml.MarkupBuilder(writer) builder.numbers { description 'Squares and factors of 10..15' for (i in 10..15) { number (value: i, square: i*i) { //#1 for ( j in 2..<i) { if (i % j == 0) { factor (value: j) //#2 } } } } } println writer http://groovyconsole.appspot.com/
  • 5. Groovy Builder DSL - HTML def writer = new StringWriter() def html = new groovy.xml.MarkupBuilder(writer) html.html { head { title 'Constructed by MarkupBuilder' } body { h1 'What can I do with MarkupBuilder?' form (action:'whatever') { for (line in [ 'Produce HTML', 'Produce XML', 'Have some fun' ]){ input(type:'checkbox',checked:'checked', id:line, '') label(for:line, line) br('') } } } } println writer
  • 6. GORM – DSL • ORM DSL – Mapping • Table, Column mapping • Relational mapping – ORM관련 설정 • • • • Cache 전략 Custom ID 전략 Composite Primary Keys Index 설정 – http://grails.org/doc/latest/guide/single.html#ormdsl • Query DSL – Basic Query • list, get, getAll – Dynamic Finders • findByXXX – – Book.findByTitle(„정글만리‟), findByTitleLike(„%정글‟) http://grails.org/doc/latest/ref/Domain%20Classes/findBy.html
  • 7. Groovy로 만든 한글 DSL Object.metaClass.을 = Object.metaClass.를 = Object.metaClass.의 = { clos -> clos(delegate) } 먼저 = { it } 표시하라 = { println it } 제곱근 = { Math.sqrt(it) } 먼저 100 의 제곱근 을 표시하라 먼저(100).의(제곱근).을(표시하라) 출처: http://it.gilbird.com/textyle/8318
  • 8. Groovy는 왜 DSL에 강한가? • Dynamic Language – Dynamic Type num = 10; str = “20” assert num instanceof Integer assert str instanceof String – Closure • Caller에게 양보하기 – MOP(Meta Class, Expando Class) • 요술상자, 아메바 – Groovy‟s chain method calls (GEP 3) • 괄호 빼기 먼저 100 의 제곱근 을 표시하라 먼저(100).의(제곱근).을(표시하라) • JVM 기반 – Groovy는 결국 Java Class로 컴파일 – 거의 95%이상 Java와 동일하게 코딩 가능 – Java와 Groovy의 혼용
  • 9. Groovy MOP • MOP(Meta Object Protocol) – MetaObjectProtocol • http://en.wikipedia.org/wiki/Metaobject • MetaClass, ExpandoMetaClass http://mrhaki.blogspot.kr/2009/10/groovy-goodness-expando-as-dynamic-bean.html – 요술을 부리는 MOP Hooks • invokeMethod, methodMissing, get/setProperty, propertyMissing
  • 11. MOP Hooks - invokeMethod import org.codehaus.groovy.runtime.StringBufferWriter import org.codehaus.groovy.runtime.InvokerHelper class Traceable implements GroovyInterceptable { Writer writer = new PrintWriter(System.out) private int indent = 0 Object invokeMethod(String name, Object args){ writer.write("n" + ' '*indent + "before method '$name'") writer.flush() indent++ def metaClass = InvokerHelper.getMetaClass(this) def result = metaClass.invokeMethod(this, name, args) indent-writer.write("n" + ' '*indent + "after method '$name'") writer.flush() return result } } class Whatever extends Traceable { int outer(){ return inner() } int inner(){ return 1 } } def log = new StringBuffer() def traceMe = new Whatever(writer: new StringBufferWriter(log)) assert 1 == traceMe.outer() println log
  • 13. MOP Hooks – methodMissing class GORM { } def dynamicMethods = [...] // an array of dynamic methods that use regex def methodMissing(String name, args) { def method = dynamicMethods.find { it.match(name) } if(method) { GORM.metaClass."$name" = { Object[] varArgs -> method.invoke(delegate, name, varArgs) } return method.invoke(delegate,name, args) } else throw new MissingMethodException(name, delegate, args) } http://groovy.codehaus.org/Using+methodMissing+and+propertyMissing
  • 14. Groovy Closure def lineFile = new File(getClass().getResource("numbers.txt").getPath()) def sumValue = 0, multiflyValue = 1, concateValue = '' lineFile.eachLine { sumValue += Integer.parseInt(it) multiflyValue *= Integer.parseInt(it) concateValue += it } assert sumValue == 10 assert multiflyValue == 24 assert concateValue == '1234'
  • 15. 한국어 DSL로 돌아와서 Object.metaClass.을 = Object.metaClass.를 = Object.metaClass.의 = { clos -> clos(delegate) } 먼저 = { it } 표시하라 = { println it } 제곱근 = { Math.sqrt(it) } 먼저 100 의 제곱근 을 표시하라 먼저(100).의(제곱근).을(표시하라) 100.제곱근 을 표시하라 출처: http://it.gilbird.com/textyle/8318
  • 16. 관련 자료 • http://notes.3kbo.com/groovy-dsls • http://en.wikipedia.org/wiki/Domainspecific_language • DSL 번역본 • 프로그래밍 그루비 • 한국어 DSL • Groovy for Domain-Specific Languages • http://en.wikipedia.org/wiki/Metaobject • http://groovy.codehaus.org/api/overviewsummary.html • Groovy Grails 의 좋은 점 • ★ Groovy