Book Image

Groovy for Domain-Specific Languages

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages

By: Fergal Dearle

Overview of this book

<p>You may already be aware that the Java virtual machine runs on everything from the largest mainframe to the smallest microchip and supports almost every conceivable application. What you may not realize is that to develop software in some of these scenarios requires a targeted, single purpose language, a Domain Specific Language. The popular scripting language Groovy can be used to create a Domain Specific Language that can run directly on the JVM alongside regular Java code.This comprehensive tutorial will take you through the design and development of Groovy-based Domain Specific Languages. It is a complete guide to the development of several mini-DSLs with a lot of easy-to-understand examples. This book will help you to gain all of the skills needed to develop your own Groovy-based DSLs, as it guides you from the basics through to the more complex meta-programming features of Groovy. The focus is on how the Groovy language can be used to construct domain-specific mini-languages. Practical examples are used throughout to de-mystify the seemingly complex language features and to show how they can be used to create simple and elegant DSLs. The examples include a quick and simple Groovy DSL to interface with Twitter.The book concludes with a chapter focusing on integrating Groovy-based DSLs in such a way that the scripts can be readily incorporated into the readers' own Java applications. The overall goal of this book is to take Java developers through the skills and knowledge they need to start building effective Groovy-based DSLs to integrate into their own applications.</p>
Table of Contents (15 chapters)
Groovy for Domain-Specific Languages
Credits
About the Author
About the Reviewers
Preface
Free Chapter
1
Introduction to DSL and Groovy
Index

Groovy improvements


So far we have been using Twitter4J as a vanilla API, with a smattering of Groovy, so we have not been bringing any of the Groovier features to bear. Now that we know a little bit about the API, let's try to improve our usage by using some Groovy features. In this section, we are going to progressively improve our usage of the Twitter4J APIs by selectively using the features that Groovy provides. One of the most obvious features to use is Closures.

A Groovier way to find friends

In the previous examples, we iterated over our friends and printed out their details. What if we were to provide a method that takes a closure to apply to each friend or follower? In this example, we add these methods to a script, along with a follow method, to follow another Twitter user. We can use the eachFollower or eachFriend methods to list our current connections.


import twitter4j.*

def twitterId = "MyTwitterUserName"
def password = "MyTwitterPassword"

// Get a twitter connection...