Java

Groovy-licious!

So, Groovy 1.0 is finally here! If you asked me a year ago, I would have said that I was just not interested in Groovy. I thought it was a dead language, and I had better things to focus on. It seemed like a great idea, but just not going anywhere. But, thanks to the committed team of developers, it has finally shaken off the vapors.

Scott Hickey, lead developer of the Groovy Eclipse plugin, has been gently pushing me to learn the language for a long time now. And, it has piqued my interest a few times, but never to the point of actually writing some code.

At our January OJUG meeting earlier this week, we had a group discussion about Groovy and how far it has come. I made a mental note to sit down and give it a go-around… kick the tires so to speak. And, yesterday I had the chance to sit down with Scott for lunch, and he went through the Groovy Eclipse Plugin with me. He showed me where things are at, and what I can do to help out.

And finally last night I sat down and wrote some Groovy. As with most languages, I started out with my favorite little program: Pegs. If you are not familiar with the game, it is basically a triangular board with fifteen holes in it, also in the shape of a triangle:

    *
   * *
  * * *
 * * * *
* * * * *

You start the game with one empty hole, and the rest filled with pegs. The object of the game is to jump a peg over another peg into an empty hole, repeating until there are no more moves left. Obviously the goal is to get down to just one peg.

Here is the code for the Board object (Board.groovy):

  1. package pegs;
  2.  
  3. class Board {
  4.         private EMPTY = 0
  5.         private SET = 1
  6.  
  7.     /*
  8.     pegs are set as follows (last row is 10 - 14)
  9.         0
  10.        1 2
  11.       3 4 5
  12.      6 7 8 9
  13.     0 1 2 3 4
  14.     */
  15.                         
  16.        private pegs = [SET,
  17.                             SET,SET,
  18.                             SET,SET,SET,
  19.                             SET,SET,SET,SET,
  20.                             SET,SET,SET,SET,SET]
  21.                         
  22.         Board(starting_peg = 0) { pegs[starting_peg] = EMPTY }
  23.  
  24.         public isWinner() { numSetPegs() == 1 } 
  25.         public numEmptyPegs() { pegs.findAll { it == EMPTY }.size }     
  26.         public numSetPegs() { pegs.findAll { it == SET }.size   }
  27.         public pegIsSet(peg) { pegs[peg] == SET; }
  28.         public pegIsEmpty(peg) { pegs[peg] == EMPTY; }
  29.                
  30.         public Board copy() {
  31.                 def board = new Board()
  32.                 for (i in 0..14)                               
  33.                         board.pegs[i] = this.pegs[i]
  34.                 return board
  35.         }
  36.  
  37.         public hash() { pegs.join(“”) }
  38.        
  39.         public forDisplay() {
  40.                 “”
  41.                      ${pegs[0]}
  42.                     ${pegs[1]} ${pegs[2]}
  43.                    ${pegs[3]} ${pegs[4]} ${pegs[5]}
  44.                   ${pegs[6]} ${pegs[7]} ${pegs[8]} ${pegs[9]}
  45.                  ${pegs[10]} ${pegs[11]} ${pegs[12]} ${pegs[13]} ${pegs[14]}
  46.                 ““”
  47.         }
  48.                        
  49.        
  50.         private static MOVES = [
  51.                    new Move(0,3,1), new Move(0,5,2),
  52.                    new Move(1,6,3), new Move(1,8,4),
  53.                    new Move(2,7,4), new Move(2,9,5),
  54.                    new Move(3,0,1), new Move(3,10,6), new Move(3,12,7), new Move(3,5,4),
  55.                    new Move(4,11,7), new Move(4,13,8),
  56.                    new Move(5,0,2), new Move(5,12,8), new Move(5,14,9), new Move(5,3,4),
  57.                    new Move(6,1,3), new Move(6,8,7),
  58.                    new Move(7,2,4), new Move(7,9,8),
  59.                    new Move(8,6,7), new Move(8,1,4),
  60.                    new Move(9,2,5), new Move(9,7,8),
  61.                    new Move(10,3,6), new Move(10,12,11),
  62.                    new Move(11,4,7), new Move(11,13,12),
  63.                    new Move(12,10,11), new Move(12,3,7), new Move(12,5,8), new Move(12,14,13),
  64.                    new Move(13,11,12), new Move(13,4,8),
  65.                    new Move(14,5,9), new Move(14,12,13)
  66.                  ]
  67.        
  68.         public List availableMoves() {  MOVES.findAll { isValidMove(it) } }
  69.  
  70.         public isValidMove(move) {
  71.                 return this.pegIsEmpty(move.to) &&
  72.                            this.pegIsSet(move.from) &&
  73.                            this.pegIsSet(move.over)
  74.         }
  75.        
  76.         public makeMove(move) {
  77.                 if (availableMoves().contains(move)) {
  78.                         this.emptyPeg(move.from)
  79.                         this.setPeg(move.to)
  80.                         this.emptyPeg(move.over)
  81.                 }
  82.         }
  83.        
  84.         private setPeg(peg) { pegs[peg] = SET }
  85.         private emptyPeg(peg) { pegs[peg] = EMPTY }
  86. }
  87.  
  88. class Move {
  89.  
  90.         protected from;
  91.         protected to;
  92.         protected over;
  93.        
  94.         Move(_from, _to, _over) {
  95.                 from = _from;
  96.                 to = _to;
  97.                 over = _over;
  98.         }
  99.  
  100. }

This code hits a ton of features that differentiate Groovy from Java:

  • Lines 4,5: Right away we see something strange. Where did the type go?
  • Line 16: Whats going on here? Not only are we not giving a type for the variable, but we also are assigning it what looks like a list…. huh.
  • Line 22: This must be the constructor for the Board class… but look! the method argument doesn’t have a type! and it allows you to set default value!
  • Line 24: Ok, so where did the return statement go?
  • Lines 25,26: Ok, Stop! Whats going on here? This is where it all starts to become gravy. So far we’ve see how Groovy simplifies our Java by getting rid of types here and there, and allows us easier creation of Lists, and the ability to ignore return statements. Now, we are seeing the Lisp nature of Groovy:
    1. public numEmptyPegs() { pegs.findAll { it == EMPTY }.size }

    This method is returning the number of empty pegs on the board… but how? It is passing a closure to the findAll() method, which then iterates the list of pegs and calls the closure on each. The closure must (in this case) return a predicate (boolean), and only the positives are added to a list which is returned, only to have the size property actually returned to the caller.

  • Line 31: Whats with the def keyword? Thats needed inside the methods to def a method scoped variable… I think there is more to it than that, but that is what I know so far.
  • Line 32: Whats with the 0..14 business? Thats a Range. Like Python, Ruby, et al.
  • Line 37: Yay! We have joins!
  • Line 40: Three quotes? wtf?!?! This is the demarcation of a multiline string. Something I have wished and prayed for (and man I do not pray for a lot) since I first experienced XML. This alone makes me quiver. Yes, I said quiver.
  • Line 41: ${pegs[0]}…. I see… its doing text replacement with the value from the pegs list… sweetness!

Everything else is pretty much either been discussed by the above, or is straight forward enough to not require too much more explanation.

In case you were interested, here is the test code. Groovy makes testing so much nicer than Java. This is not a great example, but imagine what the triple-quote feature can do for you…

  1. package pegs;
  2.  
  3. class BoardTest extends GroovyTestCase {
  4.  
  5.         void testBoardInitialized() {
  6.                 def board = new Board()  
  7.                 assert board.numEmptyPegs() == 1
  8.                 assert board.numSetPegs() == 14
  9.         }
  10.        
  11.         void testBoardHasMove() {
  12.                 def board = new Board()
  13.                 assert board.availableMoves().size == 2
  14.         }
  15.  
  16.         void testBoardMove() {
  17.                 def board = new Board()
  18.                 board.makeMove(board.availableMoves()[0])
  19.                 assert board.numEmptyPegs() == 2
  20.         }
  21.        
  22.         void testBoardCopy() {
  23.                 def board = new Board()
  24.                 def board2 = board.copy()
  25.                
  26.                 assert board.hash() == board2.hash()
  27.                
  28.                 board.makeMove(board.availableMoves()[0])
  29.                 assert board.hash() != board2.hash()
  30.                
  31.                 board2.makeMove(board2.availableMoves()[0])
  32.                 assert board.hash() == board2.hash()   
  33.         }
  34.                
  35.         void testBoardWalk() {
  36.                 def board = new Board()
  37.  
  38.                 board.makeMove(board.availableMoves()[0])
  39.                 board.makeMove(board.availableMoves()[0])
  40.                 board.makeMove(board.availableMoves()[0])
  41.                 board.makeMove(board.availableMoves()[0])
  42.                 board.makeMove(board.availableMoves()[0])
  43.                 board.makeMove(board.availableMoves()[0])
  44.                 board.makeMove(board.availableMoves()[0])
  45.                 board.makeMove(board.availableMoves()[0])
  46.                 board.makeMove(board.availableMoves()[0])
  47.                 board.makeMove(board.availableMoves()[0])
  48.                 board.makeMove(board.availableMoves()[0])
  49.  
  50.                 assert board.availableMoves().size == 0
  51.                 assert board.numSetPegs() == 3
  52.                 assert !board.isWinner()
  53.         }
  54.        
  55. }

The Board class does not really do much for you. It’s really just a state object: It gives you all of the information you need, but needs an external object to tell it whats going on. So, part of this project always entails writing a Solver to figure out all of the different winners and board states. Its a really simple Game Theory system that looks at all of the possible states of the board. So, finally, here is Solver.groovy:

  1. package pegs;
  2.  
  3. winners = 0
  4. boardCount = 0
  5. boards = new HashMap()
  6.  
  7. for(peg in 0..14) {
  8.         board = new Board(peg)
  9.         println \nStarting board(${peg})”
  10.         walkAvailableMoves(board)
  11. }
  12.  
  13. def walkAvailableMoves(board) {
  14.  
  15.         if ( boards.get(board.hash()) != null )
  16.                 return
  17.        
  18.         boards[board.hash()] = board
  19.         boardCount++
  20.         moves = board.availableMoves()
  21.         if (moves.size == 0 && board.numSetPegs() == 1) {
  22.                 winners++
  23.                 return
  24.         }
  25.        
  26.         moves.each { move ->
  27.                 newBoard = board.copy()
  28.                 newBoard.makeMove(move)
  29.                 walkAvailableMoves(newBoard)
  30.         }
  31. }
  32.  
  33. println “”
  34. println “boards: ${boardCount}”
  35. println “winners: ${winners}”

A little recursion to set the heart a-flight. Ooookay. As you can see, this is, as Bob Ross would say “just a happy little Groovy script”. (Sorry, we don’t have cable, so we are pretty much left with PBS). The only thing that may stick out a little more, and something that I did not mention above, is that there is not one semicolon in this whole script. This is typically the case with Groovy. The only time it is necessary is when you are putting multiple code statements on the same line.

Some thoughts

As indicated above, I was not a big fan of Groovy, and instead decided to go the Ruby Way. However, I think I have found the language I was looking for when I went to Ruby, and its called Scheme. Oops.. I um… Ah crap.

Seriously, Groovy is a great addition to the JDK. I was surprised to see many of the Rubyisms that I have come to love expressed in the VM that has inhabited my career for the last 7 years. I am really excited by the possibilities that adding Groovy to my repertoire will provide.

If you haven’t already, I suggest you go out and get the Groovy in Action book, and while you are at it, download the Getting Started in Grails book from InfoQ.

I have already decided what my first Grails project will be… I just hope I have enough time this weekend to get the ball rolling on it.

General
Groovy
Java
OJUG
Software Development
Thought

Comments (5)

Permalink

What is Success in the Enterprise?

I got a comment on my James McGovern::Thought Leadershit blog post earlier today, ostensibly from James himself, that I feel compelled to respond to:

Don’t have such a low threshold for measuring success. Success is Java, .NET, XML, Web Services, SOA, etc. Ruby has potential and an upward trajectory but can’t yet be called successful.

In terms of getting large enterprises whose primary business model isn’t technology involved in Ruby benefits Ruby by the simple fact that this demographic represents 90% (The masses) of all IT folks. More importantly, this same demographic has 590% more capital than the 10% that Ruby currently has. Capital allows folks to accelerate the growth, features and adoption of all the hard work the Ruby community put into it.

You should noodle this thought and even if you agree slightly, you should amplify it in your next blog entry…

I slightly agree with the above, mostly with the demographics and the problems those demographics cause. Not sure about the math…. However, what I really want to address is not the demographics… those are a causal by-product the misunderstanding evident in these statements:

Don’t have such a low threshold for measuring success. Success is Java, .NET, XML, Web Services, SOA, etc. Ruby has potential and an upward trajectory but can’t yet be called successful.

My definition of success in the enterprise has absolutely nothing to do with the technology used. Technology is nothing more than an enabler for the solutions set forth by the organization to accomplish its goals. Java, .Net, XML, Web Services, SOA, and yes, even Ruby are all just tools (and fads) that we have at our disposal at this point in time that help accomplish these goals. They are not the success factors themselves.

I am much more concerned with providing value and efficiencies to the organization. Solving problems matters more then the technology used.

What I value more than the programming language

  1. Right sized solutions to the right problems. It is so easy to build the wrong sized solution, buts worse when its not even the right problem.
  2. Simplicity Simplicity is a mindset. But lets not mistake it for “Do the simplest thing that could possibly work.” Do the simplest thing that can be maintained for 10 years.
  3. Maintainability I am sick and tired of hearing about brand spanking new projects using Struts, because thats what people know. But, on the other hand, if you can see struts still being used (and supported) at the EOL for your project, by all means. Typically I prefer to weigh my decisions on what is the latest, with the most likelyhood to succeed. Failing that (which most frameworks do), I want to know how bad (unreadable) the frameworks code is… good sign of how easy it will be to fix problems when you are on your own.
  4. Flexibility I want flexibility in my language, my IDE, my organization, and not least of which: my system’s architecture.
  5. Structure But, you cannot be all flexibility. Think of your app as a piece of Bamboo. Simple, elegant, solid, and flexible in the wind.
  6. Understanding The team must be able to read my code. Everyone (devs, admins, users, everyone) must understand the vision of the app. Without this, you have people doing things that will invariably be incongruent with the vision and goals of the team and organization.

In essence, I want everyone to think about what they are doing, and try to come up with the simplest, most maintainable system they can. I think that that is difficult in every language, and in fact I think it transcends language. This is the Silver Bullet problem (there isn’t one). So, all I can do is try to design the system the best I can, and then use a language that gives me the best Thought to Expression ratio for my solution.

Thought to Expression Ratio

I’ve mentioned this a couple of times before. Thought to Expression Ratio is a very subjective measure of how much expression is needed to convey a thought, with a ratio of 1:1 being perfect expression of a thought and 1:0 being the no expression capable of the thought.

As an example, remember the old saying “A picture is worth a thousand words”. Now, if only we had a programming language that could do that. Well, we do in a way. This is were Domain Specific Languages come into play. We can bring the programming system closer to the thoughts of the organization, and in so doing, raise the Thought to Expression ratio. And right now, there are few languages that give me the flexibility to define a DSL easily, with Ruby being the one with the most interest pointed in its direction.

Durability

By day I am a Enterprise Java developer/architect. By night I play with Ruby, and Smalltalk, and other languages that intrigue me. Why? Because Java will not be around forever. Java is indeed the next COBOL. In fact, so is Ruby. And C++, and VB, and .Net. and ….

I am a proponent of Ruby, though not as much as one might think given some of my previous posts. I value the flexibility that Ruby gives me, but I also hate the sheer power with which Ruby allows a person to write the most horrendously ugly code this side of perl. Indeed, this is what could very well be the downfall of Ruby.

Success

In the end, success on an Enterprise application can only be determined by the organization and teams involved. This is a hard problem, especially the more stakeholders involved in the definition of success. And, to me, that has nothing to do with the languages involved.

Agile
Design
General
Java
Ruby
Self
Software Development
Thought

Comments (2)

Permalink

Porous interface design

Which do you think is better?

this:

  1. public interface Scheduler {
  2.   // schedule job to deliver the domain object represented by the domainId at scheduleDate
  3.   public void scheduleDeliver(Long domainId, Date scheduleDate);
  4.   public void scheduleReprocess(Long domainId, Date scheduleDate);
  5.   …
  6.   public void scheduleCleanUp(Long domainId, Date scheduleDate);
  7. }

or this:

  1. public interface Scheduler {
  2.   // schedule a job
  3.   public void schedule(Date runAt, Job job);
  4. }

I would say “It depends, what is in the Job class?”

  1. public interface Job {
  2.   public void run();
  3. }

Heh, ok so its an interface. What is the implementation?

  1. public class DeliveryJob implements Job {
  2.   public DeliveryJob(/* context */) {}
  3.   public void run() {
  4.       // delivery code here.
  5.   }
  6. }

Which gives you this client code:

  1. public void someMethod() {
  2.   …
  3.   SchedulerImpl.schedule(runAt, new DeliveryJob(/* context can be passed in here */));
  4.   …
  5. }

But also allows for the implementation of closures:

  1. public void someMethod() {
  2.   …
  3.   SchedulerImpl.schedule(runAt, new Job() {
  4.       // code goes here.
  5.       // context in final variables in outer "someMethod"
  6.   });
  7.   …
  8. }

Ok, so there are two different interfaces, both ostensibly providing a mechanism to schedule something to run at a later date/time. Which is better? Lets look at each in turn.

The first one is using primatives to represent the data needed for the scheduling contract, in this case a Long for a “domainId” and a Date for the “scheduledDate” to run at. Each method specifies what type of job needs to be scheduled (”scheduleDelivery”, “scheduleReplay”, etc). On the immediate surface, there is nothing that stands out as a major issue. Now, lets think about how this will need to be maintained:

  • Lets say you need to change the domainId from a Long to a “DomainKey” object. This is a huge change, of which the Scheduler interface is going to see only minor changes from, but will cause rippling effects throughout both the client and the implementation code.
  • What if you want to allow a different type of job to be scheduled? You would need to add a new interface method and a new implementation.
  • The interface leaves you (or at least me) with the impression that I would need to keep the interface pretty consistent to maintain clarity. That means that anytime I wanted to schedule some new thing, I would feel compelled to propagate the interface as it is currently implemented. If I needed to do anything that seemed inconsistent I would hesitate, and probably end up with an implementation different than I initially wanted.

The second one uses an Interface to provide the job implementation. This helps to abstract the Scheduler from the implementation details of the job. By not tying into the implementation details, it keeps it’s Single Responsibility clear: to run the given job at the given time.

The only “problems” that this implementation has is that it creates extra classes, and has the ability to be “abused” by using anonymous inner classes. Notice the use of quotations in the prior sentence to indicate the facetiousness of this argument. Surprisingly, I’ve heard this argument so many times, both directly and indirectly. In this case the argument is groundless, as there is very little in the way of extra classes; just an interface and a class per implementation. This is no big deal, and is completely outweighed by the simplicity of the design.

Another argument that I have heard with this type of discussion is that the only data needed is the primitives, so why not just send that? Well, there are a number of reasons not to do that. The first is that the primitives do not represent your domain… they are an abstraction of your domain, which is an abstraction itself. I generally prefer to keep my sanity.

The one argument I could see holding water against the second interface is if it is desirable to have a domain centered interface for scheduling these jobs. But, in this case, the solution is not to get rid of the current Scheduler interface, but to add a Domain Specific Scheduler interface:

  1. public interface DomainScheduler {
  2.   public void scheduleDelivery(Date runAt, DomainObject do);
  3.   …
  4. }

Notice that even this new interface stays away from the primitive Long domainId field from the first interface. This reduces the problems from the first interface:

  • Now, a change to the key would not require an interface change, and depending on the implementation, it may not need to change either. The client code is obviously not affected.
  • It is clearer what you are doing with the data. Even if the underlying implementation does the exact same thing, now you are not wondering why only the id field is needed.

The final two interfaces are examples of porous interface design. They allow for wider ranges of data to go through, but without the worry of incorrect data, or providing too much data (Why would you allow Object?). They also make the system more extensible without changing any of the existing code. By keeping things centered around the domain, and the Single Responsibility Principle in mind, you end up with a much simpler, more maintainable design.

Design
General
Java
Ruby
Software Development
Thought

Comments (2)

Permalink

When to use inheritance

I was just perusing my copy of Java Design: Building Better Apps and Applets by Peter Coad and Mark Mayfield and noticed a good set of rules to follow when thinking about using inheritance:

  1. “Is a special kind of”, not “is a role played by a”
  2. Never needs to transmute to be an object in some other class
  3. Extends rather than overrides or nullifies superclass
  4. Does not subclass what is merely a utility class (useful functionality you would like to reuse)
  5. Within PD(Problem Domain): expresses special kinds of roles, transactions, or devices

Update: I probably should mention that you should fulfill all or at least most of these to consider inheritance. Otherwise use composition or re-analyze your design.

General
Java
Ruby
Software Development

Comments (0)

Permalink

Changing Mindset: From Procedural to Object Oriented

Yesterday I had the chance to write some code to determine if I needed to schedule an action for later processing, or do the action immediately. I am working on a system that has a fairly well laid out component architecture, with a fairly good Business model. However, it is almost all “Controllers and Data Structures” at this point. Given my previous experiences with how people would write this type of code, it would invariably end up like this:

  1. public void someComponentMethod(Long rootModelID) {
  2.   RootModelObject root = DAOFactory.getRootModelDAO().getRootModel(rootModelID);
  3.  
  4.   // many lines of code later …
  5.  
  6.   if ( root.getExtraData() != null &&
  7.         root.getExtraData().getSchedule() != null ) {
  8.         Schedule s = root.getExtraData().getSchedule();
  9.         if ( s.getScheduleDate().after(new Date()) ||
  10.              s.getCronExpression() != null ) {
  11.                 root.setStatus(SCHEDULED);
  12.                 DAOFactory.getRootModelDAO().save(root);
  13.                // schedule for later code
  14.         }
  15.   } else {
  16.         // deliver immediately code
  17.   }
  18.   // many lines of code later …
  19. }

There are a number of issues in the above code:

  1. The interface to this method is abhorrent. I will discuss this in another post.
  2. The component knows WAY too much about the specifics for processing.
  3. Hand in hand with the above, it knows way too much about the Business Model.

This is a classic case of “Asking, not Telling”, the antithesis to the awesome article Tell, Don’t Ask, by Dave Thomas and Andy Hunt. GO NOW and read it if you haven’t.

Here is the code I ‘ve written so far:

  1. public void someComponentMethod(RootModelObject root) {
  2.         // small amount of other code
  3.  
  4.         if ( root.shouldBeScheduled() ) {
  5.                 root.setStatus(SCHEDULED);
  6.                 DAOFactory.getRootModelDAO().save(root);
  7.                 scheduleComponent.schedule(root);
  8.         }
  9.         else {
  10.                 root.setStatus(PROCESSING);
  11.                 DAOFactory.getRootModelDAO().save(root);
  12.                 nextComponent.process(root);
  13.         }
  14. }

There are few things here that are better: First, I pass in the object I want to work on… this is SO much better than having to go get the Object from some back-end store by ID. I will definitely be talking about this more in the near future. Second, I broke out the beautiful comments from the code above into separate methods, on the components that they represent. This can only make things easier in that code, which most assuredly would have otherwise been in the if block as the comments suggest. And finally the piece that got me started on this post, I moved all of the logic revolving around the Schedule behind the walls of the RootModelObject. But, I did not stop there. Since from the perspective of the RootModelObject, it is not it’s responsibility to determine if it should be scheduled, I created a shouldBeScheduled method on the ExtraData object, which then called a shouldBeScheduled() method on the Schedule object:

  1. class RootModelObject {
  2.   …
  3.   public boolean shouldBeScheduled() {
  4.         return getExtraData().shouldBeScheduled();
  5.   }
  6. }
  7.  
  8. class ExtraData {
  9.   …
  10.   public boolean shouldBeScheduled() {
  11.         return getSchedule().shouldBeScheduled();
  12.   }
  13. }
  14.  
  15. class Schedule {
  16.   …
  17.   public boolean shouldBeScheduled() {
  18.         return ( getScheduleDate().after(new Date()) ||
  19.                    getCronExpression() != null );
  20.   }
  21. }

This “string of pearls” makes it much easier to keep the code where it needs to be, while providing convenience to the component developer.

So, the code is better, but part of me says that the code really should look like this:

  1. public void someHigherLevelComponentMethod(RootModelObject root) {
  2.   …
  3.   root.schedule();
  4. }

Since technically, when you say “process immediately” you are effectively saying “schedule for processing now”. What do you think?

Books
General
Java
Software Development
Thought

Comments (2)

Permalink