Tuesday, February 20, 2007

Ruby Interfaces and Design By Contract

Interfaces in Ruby (attempted summary)


Technically speaking Ruby does not need interfaces since it is dynamically typed. Any argument list that at least satisfies the arity condition can be handed into a method.

Since people appreciate the usage of interfaces and even more Design by Contract (DbC) some mechanics were developed that mimic interfaces and certain aspects of DbC. I list them in order of increasing complexity.

(1) Document which methods a method argument must implement or its expected type.

(2) Define a module containing the methods that all raise an exception like this:

module FooInterface
def bar(a,b) raise "bar(a,b) must be overridden"; end
end

class FooClass
include FooInterface

def bar(a,b) a+b; end
end

(3) Create a framework (like the one Paul Brannan suggested here [1]) for defining interface methods and for checking that a particular instance implements these methods.

(4) Try to support even more of DbC by dealing with preconditions and postconditions like I tried in [2].


Recently announced 0.1 version of Ruby Design by Contract and Java style interfaces for ruby.

No comments: