Designing a Java DSEL

Garrett Rowe

Ranch Hand

Posts: 1296

posted 10 years ago

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.