Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
  • Piet Souris
  • Himai Minh

Designing a Java DSEL

Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Off and on for the past few weeks, I been playing around with making a Craps simulator in Java. Everything was going along pretty well, I had a DiceRoller object that was responsible for rolling the dice, and publishing events to all RollListeners that were registered to it.

I then created a Bet interface that extended the RollListener interface.

The tedious portion would be coding the myriad of concrete classes to represent the logic for each Bet:

The Bets would all basically do the same thing, when a RollEvent was fired, they would examine the RollEvent and see if it meant they won, lost, or just continued on. If they won, they would calculate the payout based upon the amount bet, and then transfer that amount to the player via CrapsPlayer.acceptWinnings(int). If they lost, they would do nothing but change their status to Status.LOST, and the CrapsTable would take care of unregistering them as listeners to the DieRoller. After coding about three of the concrete Bet implementations, I just got bored with the whole idea. Then I came across this paper from the jMock guys about creating an EDSL in Java. Inspired by the coolness of it all, I decided to develop my Bet system to be a blatant plagiarism of jMock's declarative style. Now I can declare all my Bets using their own *special-syntax* like:

any(int) is a static method of BetBuilder which returns a BetEvaluator object

or(BetEvaluator...) and and(BetEvaluator...) are also static methods of the BetBuilder class which accept an arbitrary number of BetEvaluators and return a BetEvaluator.

I think its clearer when I read the code exactly what the rules are for the Bet, and it makes it simple to create new Bet types with new expectations.

I'm interested in hearing what others think of this declarative style embedded in a Java program.
[ June 03, 2007: Message edited by: Garrett Rowe ]
Get meta with me! What pursues us is our own obsessions! But not this tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
    Bookmark Topic Watch Topic
  • New Topic