Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Groovy DSLS


May 14, 2021 Groovy



Groovy allows parentheses to be omitted around the parameters of the method call of the top-level statement. ls. his extension works by allowing a person to link this parenthesed method call without parentheses around the argument or the point between the link calls.

If a call is executed as bcd, this is actually equivalent to a(b) .c (d).

DSL or domain-specific languages are designed to simplify code written in Groovy and make it easy for ordinary users to understand. The following example shows the exact meaning of having a domain-specific language.

def lst = [1,2,3,4] 
print lst

The code above shows a list of numbers printed to the console using the println statement. In a domain-specific language, the command will be -

Given the numbers 1,2,3,4
 
Display all the numbers

So the example above shows the conversion of programming languages to meet the needs of domain-specific languages.

Let's look at a simple example of how we implement DSL in Groovy -

class EmailDsl {  
   String toText 
   String fromText 
   String body 
	
   /** 
   * This method accepts a closure which is essentially the DSL. Delegate the 
   * closure methods to 
   * the DSL class so the calls can be processed 
   */ 
   
   def static make(closure) { 
      EmailDsl emailDsl = new EmailDsl() 
      // any method called in closure will be delegated to the EmailDsl class 
      closure.delegate = emailDsl
      closure() 
   }
   
   /** 
   * Store the parameter as a variable and use it later to output a memo 
   */ 
	
   def to(String toText) { 
      this.toText = toText 
   }
   
   def from(String fromText) { 
      this.fromText = fromText 
   }
   
   def body(String bodyText) { 
      this.body = bodyText 
   } 
}

EmailDsl.make { 
   to "Nirav Assar" 
   from "Barack Obama" 
   body "How are things? We are doing well. Take care" 
}

When we run the program above, we will get the following results -

How are things? We are doing well. Take care

The following needs to be noted in the code implementation above -

  • Use a static method that accepts closures. This is a cumbersome way to implement DSL.

  • In the e-mail example, the class e-mail Dsl has a make method. I t creates an instance and delegates all calls in the closure to the instance. This is a mechanism where the "to" and "from" sections end the execution method in the emailDsl class.

  • Once the to() method is called, we store the text in the instance for later formatting.

  • We can now call the EmailDSL method in a simple language that is easy for end users to understand.