Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 61 ]

When passing the map directly to the Customer constructor, we can omit the map
literal square brackets, as seen here when initializing customer2. However, this is
another case where the method's parentheses cannot be omitted.


Every GroovyBean has this default built-in Map constructor. This constructor works by
iterating the map object and calling the corresponding property setter for each entry in
the map object. Any entry in map that doesn't correspond to an actual property of the
bean will cause an exception to be thrown. The beauty and simplicity of this approach
is that it allows us to have absolute flexibility when initializing beans.


We can name properties in any order that we want, and omit properties if we see fit.


This feature is often referred to as named parameters as it gives the
impression that we are providing a flexible parameter list where we
name those parameters, even though we are just passing a Map object.

Assertions


Groovy has a built-in assertion keyword assert. The assert keyword
can be used in conjunction with any Boolean conditional statement. Groovy
assertions work similarly to Java assertions, however, since Groovy 1.7, they
provide much more information about assertion failures, including a visual
representation of each subexpression in the assertion, and its corresponding
value. If the asserted statement is not true, the assert keyword can cause a
java.lang.AssertionExceptionAssertionExceptionError exception to be
thrown. Assertions have two forms:


assert 1 == 1
assert 1 == 2 : "One is not two"

This gives the following output:


java.lang.AssertionError: One is not two. Expression: (1 == 2)


The first assertion passes silently, whereas the second throws the AssertionError
exception and the test inserted after the colon is injected into the exception log for
more clarity. Groovy 1.7 introduced the "power assert". If we use the first form
of preceding assertion without the failure message, Groovy will automatically
introspect the full expression within the assertion and give a detailed breakdown
of what was wrong.


def map = [a:'a',b:'b',c:[d:'d',e:['f','g']]]
assert map.c.e[1] == 'h'
Free download pdf