Print Shortlink

DSL with Groovy, another one

In one of the earlier posts we created a simple query using Groovy DSL. Let’s implement another example as shown below using the DSL capabilities of Groovy. Let’s create User.groovy with the code shown below.

//User.groovy
Calculator.compute {
			addition 2,3
			subtraction 10,4
			multiplication 100,40	
		  }

You want to add two numbers, subtract 2 numbers, multiply 2 numbers and finally print the result of all these computations.

Understanding this code involves demystifying the Groovy syntax here. The decoded syntax is shown below.

Calculator.compute({
			addition(2,3)
			subtraction(10,4)
			multiplication(100,40)	
		  })

compute is a static method in Calculator class that accepts a closure as argument. The closure has calls to addition, subtraction and multiplication methods. Now let’s implement the Calculator class.

class Calculator {
	static results = []
	static compute(block){
		def calc = new Calculator()
		calc.with block//Key
		results.each {println it}
	}
	def addition(a,b){
		results << "Addition of ${a} and ${b} is ${a+b}"
	}
	def subtraction(a,b){
		results << "Subtraction of ${a} and ${b} is ${a-b}"
	}
	def multiplication(a,b){
		results << "Multiplication of ${a} and ${b} is ${a*b}"
	}
}

Calculator class has the addition, subtraction and multiplication methods that add the result to a collection. The compute method accepts the block of code as the argument. You can invoke the block of code by writing block(), but it would look for the addition… methods in the invoking class. In other words, the “delegate” for this closure would be the “User” class. Therefore it would look for addition… methods in the User class.

In order to change the delegate to Calculator instance, we create an instance of Calculator, clone the closure and invoke it with that Calculator instance. All these things can be implemented using one line of code using “with“.

calc.with block

The closure would now look for the addition… methods in the delegate class ie., the Calculator.

Leave a Reply