File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes OO, Patterns, UML and Refactoring and the fly likes Designing a Java DSEL Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Designing a Java DSEL" Watch "Designing a Java DSEL" New topic
Author

Designing a Java DSEL

Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Designing a Java DSEL