Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

AST Transformations


[ 218 ]

Testing the state machine DSL


With our state machine complete, we hope now that it will work as well as the hand
crafted pattern, which fortunately it does. We can test that by modifying the Spock
test used for the original state pattern classes. All we need to do is change the class
name to the name of the DSL script:


given:
def ledToggle = new LEDToggleState()

expect:
ledToggle.state == 'OFF'

when:
ledToggle.toggle()
then:
ledToggle.state == 'ON'

when:
ledToggle.toggle()
then:
ledToggle.state == 'OFF'

However, what's even better is that we now have a reusable DSL for building state
machines. What would a regular ON/OFF light switch look like in this DSL?


state: "OFF"
state: "ON"

event: "switchOn"
next = "ON"

event: "switchOff"
next = "OFF"

Note here how we can omit the when: clause from the DSL because the next state
when we switch on is always on and when we switch off is always off. We can write
a test to confirm this also works as we expect it:


given:
def ledSwitch = new LEDSwitchState()

expect:
ledSwitch.state == 'OFF'

when:

http://www.ebook3000.com
Free download pdf