Groovy for Domain-specific Languages Second Edition
Table of Contents
Groovy for Domain-specific Languages Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introduction to DSLs and Groovy
DSL – a new name for an old idea
The evolution of programming languages
General-purpose languages
Spreadsheets and 4GLs
Language-oriented programming
Who are DSLs for?
A DSL for process engineers
Stakeholder participation
DSL design and implementation
External versus internal DSLs
Operator overloading
Groovy
A natural fit with the JVM
Groovy language features
Static and optional typing
Native support for lists and maps
Closures
Groovy operator overloading
Regular expression support
Optional syntax
Groovy markup
Summary
2. Groovy Quick Start
Installing Groovy with GVM
Installing GVM
Installing GVM on Windows
How to find and install Groovy from binaries
Running Groovy
The Groovy script engine – groovy
Shebang scripts
The Groovy shell – groovysh
The Groovy console – groovyConsole
The Groovy compiler – groovyc
The Groovy IDE and editor integration
NetBeans
Eclipse
Spring STS
IntelliJ IDEA
Other IDEs and editors
Summary
3. Essential Groovy DSLs
Installing Gradle
Gradle basics
Gradle build scripts
Gradle tasks
Adding actions to tasks
Default tasks
Creating task dependencies
Built-in tasks and plugins
Plugins
The Gradle Groovy plugin
The IDEA plugin
The Eclipse plugin
Repositories
Dependencies
Spock tests
Given, when, then
Spock specification structure
Feature methods
Blocks
Fields
Fixture methods
Helper methods
Where blocks
Fixture blocks
Testing Gradle using Spock
Further reading
Summary
4. The Groovy Language
Introducing the Groovy language
The module structure
Groovy shorthand
Implicit imports
Default visibility, optional semicolon
Optional parentheses
The optional dot in method chains
Dynamic types
The optional return keyword
Properties and GroovyBeans
Assertions
Autoboxing
Strings
Regular expressions
Methods and closures
Control structures
Groovy Truth
Ternary and Elvis operators
Spaceship and Elvis operators
The switch statement
Loops
Collections
Ranges
Lists
Maps
Operators
Spread and spread-dot
Null safe dereference
Operator overloading
Summary
5. Groovy Closures
What is a closure?
Closures and collection methods
Closures as method parameters
Method parameters as DSL
Forwarding parameters
Calling closures
The implicit doCall method
Finding a named closure field
Closure parameters
Enforcing zero parameters
Parameters and the doCall method
Passing multiple parameters
Default parameter values
Implementing closures in Java
Curried parameters
Closure return values
The closure scope
The this, owner, and delegate variables
Closure composition
Closure trampoline
Closure memoization
Summary
6. Example DSL – GeeTwitter
Twitter
Working with the Twitter APIs
Using Twitter4J Java APIs
Tweeting
Direct messages
Searching
Following
Groovy improvements
A Groovier way to find friends
Groovy searching
Removing the boilerplate
Refactoring
Fleshing out GeeTwitter
Improving search
Adding a command-line interface
Adding built-in methods
Summary
7. Power Groovy DSL Features
Named parameters
Named parameters in DSLs
Command chains
Builders
The builder design pattern
Using Groovy builders
MarkupBuilder
Namespaced XML
The GroovyMarkup syntax
GroovyMarkup and HTML
Using program logic with builders
Builders for every occasion
NodeBuilder
Using GPath to navigate a node tree
SwingBuilder
Method pointers
Metaprogramming and the Groovy MOP
Reflection
Groovy reflection shortcuts
Expandos
Categories
Traits
MetaClass
Pretended methods – MetaClass.invokeMethod
Understanding this, delegate, and owner
How builders work
ExpandoMetaClasses
Replacing methods
Adding or overriding static methods
Dynamic method naming
Adding overloaded methods
Adding constructors
Summary
8. AST Transformations
What is an AST
Compiler phases
Local AST transformations
Using ASTBuilder
Build from code
Build from Spec
Traits to the rescue
Global AST transformations
A finite state machine DSL
The state machine pattern
A state machine AST transformation
Handling errors – compile errors
Building the new AST nodes
Testing the state machine DSL
Compiling and packaging an AST transformation
Summary
9. Existing Groovy DSLs
Grails object relational mapping – GORM
Grails quick start
The grails-app directory
Building a GORM model
Using domain classes
Modeling relationships
Associations
One-to-one
Constraints
One-to-many
Many-to-many
Composition
Inheritance
Mapping
Querying
Dynamic finders
GORM as a DSL
Spock as a DSL
Spock
JUnit
Summary
10. Building a Builder
The builder code structure
Closure method calls
The resolve strategy – OWNER_FIRST
Pretended methods
invokeMethod
methodMissing
The closure delegate
BuilderSupport
BuilderSupport hook methods
A database builder
FactoryBuilderSupport
Summary
11. Implementing a Rules DSL
Groovy bindings
Exploiting bindings in DSLs
Closures as built-in methods
Closures as repeatable blocks
Using a specification parameter
Closures as singleton blocks
Using binding properties to form context
Storing and communicating results
Building a rewards DSL
Designing the DSL
BroadbandPlus
Reward types
The reward DSL
Handling events – deferred execution
Convenience methods and shorthand
The offers
The RewardService class
The BroadbandPlus application classes
Testing with Spock
Summary
12. Integrating It All
Groovy as a teaching language
Hiding complexity
A game DSL for kids
A game DSL – goals
Architecture and technology choices
TicTacToe in a DSL
Implementing the AST transform
Building the game engine pattern
Testing the DSL
Class loading issues
Gradle subprojects
Debugging
The game server
Integrating with Spring Boot server
Controller annotations
JSONP
Loading the DSL
Spring Data mapping for MongoDB
The Game UI
Summary
Index
Groovy for Domain-specific Languages Second Edition
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2010
Second edition: September 2015
Production reference: 1230915
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-540-4
www.packtpub.com
Author
Fergal Dearle
Reviewers
David W Millar
Pietro Martinelli
Jason Winnebeck
Commissioning Editor
Erol Staveley
Acquisition E...