DZone
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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Clean Unit Testing
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Automatic Code Transformation With OpenRewrite
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  1. DZone
  2. Coding
  3. Languages
  4. A Groovy DSL from Scratch in Two Hours

A Groovy DSL from Scratch in Two Hours

Through DZone I found Architecture Rules, a lovely little framework that abstracts JDepend. Architecture Rules is configured via its own XML schema.

By 
Steven Devijver user avatar
Steven Devijver
·
Jan. 20, 08 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
62.5K Views

Join the DZone community and get the full member experience.

Join For Free

Today is my lucky day. Through DZone I found Architecture Rules, a lovely little framework that abstracts JDepend.

Architecture Rules is configured via its own XML schema. Here's an example:

<architecture>  
    <configuration>  
        <sources no-packages="exception">  
            <source not-found="exception">spring.jar</source>  
        </sources>  
        <cyclicaldependency test="true"/>
    </configuration>  
    <rules>  
        <rule id="beans-web">  
            <comment>
                org.springframework.beans.factory cannot depend on 
                org.springframework.web
            </comment>  
            <packages>  
                <package>org.springframework.beans.factory</package>  
            </packages>  
            <violations>  
                <violation>org.springframework.web</violation>  
            </violations>  
        </rule>  
        <rule id="must-fail">  
            <comment>
                org.springframework.orm.hibernate3 cannot depend on
                org.springframework.core.io
            </comment>  
            <packages>  
                 <package>org.springframework.orm.hibernate3</package>  
            </packages>  
            <violations>  
                <violation>org.springframework.core.io</violation>  
            </violations>  
        </rule>  
    </rules>  
</architecture>

On top of the nice configuration API I wrote my own Groovy DSL. And I did it in 2 hours.

architecture {
    // cyclic dependency check enabled by default
    jar "spring.jar"

    rules {
        "beans-web" {
            comment = "org.springframework.beans.factory cannot depend on org.springframework.web"
            'package' "org.springframework.beans"
            violation "org.springframework.web"
        }
        "must-fail" {
            comment = "org.springframework.orm.hibernate3 cannot depend on org.springframework.core.io"
            'package' "org.springframework.orm.hibernate3"
            violation "org.springframework.core.io"
        }
    }
}

Now I will show you how I've build this DSL so you can learn how you can write your own.

This DSL like many others in Groovy uses the Builder syntax: method calls that take a Closure as argument. As a reminder, a Closure is at the same time a function and an object. You can call and execute it as a function and call methods and properties as an object.

To support this builder syntax you have to write methods that take as last argument a groovy.lang.Closure object:

// example of builder syntax
someMethod {

}

// signature of method that will be called
// can be void or return an object, that's up to you
void someMethod(Closure cl) {
    // do some other work
    cl() // call Closure object
}

The first step is to create a class that will evaluate DSL configuration files. I've called it GroovyArchitecture:

class GroovyArchitecture {
    static void main(String[] args) {
        runArchitectureRules(new File("architecture.groovy"))
    }
    static void runArchitectureRules(File dsl) {
        Script dslScript = new GroovyShell().parse(dsl.text)
    }
}

The GroovyArchitecture class will evaluate a DSL file and get a groovy.lang.Script object. If the class is launched through its main() method it will read the architecture.groovy file in the current directory.

Now that I've got the skeleton in place I have to add the first method that will be called by the DSL script: the architecture() method.

The first method is usually the trickiest to implement, as when the script is executed this method will be called on the Script object. Needless to say this object does not have an architecture() method. Groovy does provide a way to add it through the MOP or Meta-Object Protocol.

Difficult words for an easy enough technique. Each object in Groovy has a MetaClass object that handles all method calls that are executed on that object. What we need to do is create a custom MetaClass object and assign it to the script object.

class GroovyArchitecture {
    static void main(String[] args) {
        runArchitectureRules(new File("architecture.groovy"))
    }
    static void runArchitectureRules(File dsl) {
        Script dslScript = new GroovyShell().parse(dsl.text)

        dslScript.metaClass = createEMC(dslScript.class, {
            ExpandoMetaClass emc ->


        })
        dslScript.run()
    }

    static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
        ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)

        cl(emc)

        emc.initialize()
        return emc
    }
}

Let's go over this step by step. I've added the createEMC() method which creates a groovy.lang.ExpandoMetaClass object, initializes it and returns it (lines 16 to 23). Before initializing it the object is passed to a Closure (line 19). This Closure is passed as an argument to the createEMC() method (lines 8 to 12).

I'm using the Closure as a callback to customize the ExpandoMetaClass object while hiding the details of creating and configuring it. The return value of the createEMC() method is assigned to the metaClass property of the DSL Script object (line 8).

I'm also calling the run() method on the DSL Script object to execute the DSL script (line 13).

The ExpandoMetaClass class comes with Groovy 1.1 and later and allows us to add custom methods via the Meta-Object Protocol. In other words, we can add any method we want to any object we want by assigning an ExpandoMetaClass object to the metaClass property of another object.

Now, how to add these methods then? I need to configure the ExpandoMetaClass object:

class GroovyArchitecture {
    static void main(String[] args) {
        runArchitectureRules(new File("architecture.groovy"))
    }
    static void runArchitectureRules(File dsl) {
        Script dslScript = new GroovyShell().parse(dsl.text)

        dslScript.metaClass = createEMC(dslScript.class, {
            ExpandoMetaClass emc ->

            emc.architecture = {
                Closure cl ->


            }
        })
        dslScript.run()
    }

    static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
        ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)

        cl(emc)

        emc.initialize()
        return emc
    }
}

I'm assigning a Closure to the architecture property of the ExpandoMetaClass object (lines 11 to 15). This Closure will be the implementation of the architecture() method and will also determine the arguments that method accepts. By assigning the architecture property I've added this method to the DSL script via the MOP: architecture(Closure).

So, right now I can execute this DSL script without errors:

// architecture.groovy file
architecture {

}

Next step is to add the Architecture Rules classes to the mix.

import com.seventytwomiles.architecturerules.configuration.Configuration
import com.seventytwomiles.architecturerules.services.CyclicRedundancyServiceImpl
import com.seventytwomiles.architecturerules.services.RulesServiceImpl

class GroovyArchitecture {
    static void main(String[] args) {
        runArchitectureRules(new File("architecture.groovy"))
    }
    static void runArchitectureRules(File dsl) {
        Script dslScript = new GroovyShell().parse(dsl.text)

        Configuration configuration = new Configuration()
        configuration.doCyclicDependencyTest = true
        configuration.throwExceptionWhenNoPackages = true

        dslScript.metaClass = createEMC(dslScript.class, {
            ExpandoMetaClass emc ->

            emc.architecture = {
                Closure cl ->


            }
        })
        dslScript.run()

        new CyclicRedundancyServiceImpl(configuration)
            .performCyclicRedundancyCheck()
        new RulesServiceImpl(configuration).performRulesTest()
    }

    static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
        ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)

        cl(emc)

        emc.initialize()
        return emc
    }
}

The Configuration class takes the configuration for the Architecture Rules framework. I'm assigning two useful default values (lines 12 to 14). The CyclicRedundancyServiceImpl and RulesServiceImpl classes perform the actual checks on the source code (lines 27 and 29).

The next step is to add the location of classes or JARs. I want to extend the DSL like this:

// architecture.groovy file
architecture {
    classes "target/classes"
    jar "myLibrary.jar"
}

Adding these two methods is more straightforward since I don't have to use ExpandoMetaClass anymore. Instead, I'm assigning a delegate to the Closure object that is passed as argument when executing the architecture() method.

Before assigning a delegate however I have to create a new class: ArchitectureDelegate. Any methods and properties that are called inside the Closure will be delegated to an ArchitectureDelegate object. Hence, the ArchitectureDelegate class has to provide two methods: classes(String) and jar(String).

import com.seventytwomiles.architecturerules.configuration.Configuration

class ArchitectureDelegate {
    private Configuration configuration

    ArchitectureDelegate(Configuration configuration) {
        this.configuration = configuration
    }

    void classes(String name) {
        this.configuration.addSource new SourceDirectory(name, true)
    }

    void jar(String name) {
        classes name
    }
}

As you can see the classes() and jar() methods are actual methods on the ArchitectureDelegate class. Next step is to assign an ArchitectureDelegate object as delegate to the Closure passed to the architecture() method.

import com.seventytwomiles.architecturerules.configuration.Configuration
import com.seventytwomiles.architecturerules.services.CyclicRedundancyServiceImpl
import com.seventytwomiles.architecturerules.services.RulesServiceImpl

class GroovyArchitecture {
    static void main(String[] args) {
        runArchitectureRules(new File("architecture.groovy"))
    }
    static void runArchitectureRules(File dsl) {
        Script dslScript = new GroovyShell().parse(dsl.text)

        Configuration configuration = new Configuration()
        configuration.doCyclicDependencyTest = true
        configuration.throwExceptionWhenNoPackages = true

        dslScript.metaClass = createEMC(dslScript.class, {
            ExpandoMetaClass emc ->

            emc.architecture = {
                Closure cl ->

                cl.delegate = new ArchitectureDelegate(configuration)
                cl.resolveStrategy = Closure.DELEGATE_FIRST

                cl()
            }
        })
        dslScript.run()

        new CyclicRedundancyServiceImpl(configuration)
            .performCyclicRedundancyCheck()
        new RulesServiceImpl(configuration).performRulesTest()
    }

    static ExpandoMetaClass createEMC(Class clazz, Closure cl) {
        ExpandoMetaClass emc = new ExpandoMetaClass(clazz, false)

        cl(emc)

        emc.initialize()
        return emc
    }
}

The Closure's delegate property takes the ArchitectureDelegate object (line 22). The resolveStrategy property is set to Closure.DELEGATE_FIRST (line 23). This means any method or property called inside the Closure will be delegated to the ArchitectureDelegate object. I call the Closure on line 25.

Time to add the rules() method to the DSL:

// architecture.groovy file
architecture {
    classes "target/classes"
    jar "myLibrary.jar"

    rules {

    }
}

Where to add this method? To the delegate object of course.

import com.seventytwomiles.architecturerules.configuration.Configuration

class ArchitectureDelegate {
    private Configuration configuration

    ArchitectureDelegate(Configuration configuration) {
        this.configuration = configuration
    }

    void classes(String name) {
        this.configuration.addSource new SourceDirectory(name, true)
    }

    void jar(String name) {
        classes name
    }

    void rules(Closure cl) {
        cl.delegate = new RulesDelegate(configuration)
        cl.resolveStrategy = Closure.DELEGATE_FIRST

        cl()
    }
}

Adding the rules() method to the DSL syntax is as easy as adding the rules() method to the ArchitectureDelegate class (line 18 to 23). And so on. Each new Closure in the DSL gets its own delegate object. You'll find the DSL script and the parsing code attached to this post.

Happy coding!

Domain-Specific Language Object (computer science) Groovy (programming language) Scratch (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?
  • Clean Unit Testing
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!