Pages

Friday, March 15, 2013

State pattern : Java and Ruby comparison

I've been working with Java as a programming language for long now and just started learning Ruby a few weeks back. Here I present a comparison between the two while trying to implement a basic State pattern. The reason I compare these examples is that they highlight the difference in the way these languages enable Design by contract.

In both examples clients of the StateExample class call its transition() method with a criteria parameter to change it's state. 

Java implementation

The StateExample class has a reference to an implementation of the IState interface. The transition() method delegates itself to the evaluate() method of the IState implementation which evaluates the criteria and returns either itself or a new IState implementation. Basically this allows the Implementation of the State to be abstracted to the interface IState and the StateExample class works on the contract specified by IState.

Ruby Implementation

Let's now look at the Ruby implementation of the same example. The StateExample class looks almost similar to it's Java counterpart. What's noticeable here is the absence of the equivalent of interface IState
Duck typing in Ruby allows this. The object referenced by the current_state variable only needs to contain an evaluate() method. The contract is therefore on the behaviour of the value of current_state rather than it's type.

Conclusion

Design by contract seems to be subtler and more implied in Ruby as compared to being typed in Java. For someone coming from Java, programming in a dynamically typed language like Ruby separates the concepts of Object oriented programming and Java language semantics. I can't help imagining Morpheus asking me to "Free your mind" :).

Monday, March 11, 2013

Test Driven (Design &) Development

I have been following Test Driven Development (TDD) for a few months now. 

Some of the direct benefits that I've seen are:

  • Highly improved productivity due to minimal & accurate development.
  • Highly improved code quality as I can refactor without fear of breaking something.
  • A mental pat on my back whenever my tests are green-lighted :). i.e it is fun.
I have been trying to spread this practice at the workplace for the past few months with little success. My "sales pitch" typically revolves around the points mentioned above and I've had little success.

As I use TDD more and more, what I have come to realize is that not only has my code become cleaner now, my designs are more robust and flexible. I think to a large extent this is due to the fact that TDD tends to negate the effects of design prejudices.

Here is another blog that echoes some of the points mentioned here.

I am currently reading Test Driven Development : By Example by Kent Beck . Will publish a review once done reading. Something that has really taught me TDD has been the XP episode by Robert C. Martin and Robert S. Koss.