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
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