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.


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" :).

No comments: