Wednesday, September 26, 2012

Ruby Interfaces

Interfaces!

I've been using jRuby for these past three months, and I like it. It's concise, readable, structured well, and Rails is awesome. There's a few things that I keep beating my head against, like what they named the functional collection methods (zip?  really?), but overall I think it's a really neat way to write code.

The one thing that really annoys me is the lack of interfaces though. I've looked all over the net, and although there are a few ruby gems that provide interfaces, they're not commonly used and most people complain that they're not needed. Which from a certain perspective is true.


I managed to find the definition that I was looking for in the Java tutorials:  "Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler." Since ruby doesn't have build time nor a compiler, many people consider interfaces unnecessary. Personally, I think they're missing the first part of that definition. Just because the contract isn't enforced by the compiler doesn't mean that it's worthless.

One weekend I decided to implement Dijkstra's shortest path in Ruby. It was about twenty lines long, elegant and readable, and reasonably fast. (I didn't work in a heap, so it was n^2 instead of n log n) Great exercise, and fun was had by all.

Then I looked at the code, and tried to figure out how I would make this code reusable. The biggest problem was that the algorithm was tightly bound to my data - the nodes had to handle very specific messages in order to work properly.  In Java, this would be a simple problem to fix - extract a node interface from the implementation and then everyone who wants to use your algorithm simply adds that interface to the node class. Granted, I can't find a Java implementation that's less than 200 lines, but I'm focusing on the interfaces here.

I haven't figured out a way in Ruby to make this work like I want. There seem to be three common options for Ruby.
  1. If the writer is very thorough then they may actually put a description up so you know what to implement.
  2. People can copy your algorithm and modify it to match their needs.
  3. Mostly you just have to read the source code to figure out how to match your data to their implementation.
This is to me where the interface really becomes necessary. I want to know how to work with your code, without knowing how it is implemented. 

1 comment: