Method validation, preconditions and postconditions in Ruby
I've been playing around some more with Ruby as a result of my work on TweetSum and in an effort to validate the behaviours of some of our code I'm coming to the conclusion that some kind of validation/precondition/postcondition framework might be useful. I really want to be able to do things like the following:
class MyClass
def my_method()
pre {
# Preconditions go here.
}
post {
# Postconditions go here.
}
# The method body
end
end
This is roughly the approach taken by Ruby Design by Contract and I may yet adopt this library. However, along the way I came up with my own solution which I'm going to describe quickly here. I'm sure there are problems with it (apparent from the obvious lack of syntactic sugar) that I haven't anticipated yet, but I feel like posting this anyway.
You just need to require validation.rb and define your functions or methods as follows:
class MyClass
define_validated_method(:my_method, lambda {|a, b, c, d|
# Preconditions
validate_is_string(a, "a must be a string of greater than 5 characters") {a.length > 5}
validate_is_string(b, "b must be a string")
validate_is_string(c, "c must be a string")
validate_is_string(d, "d must be a string")
}, lambda {|return_value|
# Postconditions
validate_is_fixnum(return_value, "return_value must be a Fixnum greater than 0") {return_value > 0}
}) do |a, b, c, d|
return a.length + b.length + c.length + d.length
end
end
Normally you'd use def my_method(a, b, c, d) but this wrapper function takes care of injecting the precondition and postcondition code into the method using the define_method function internally.
I hope this makes some kind of sense to you!
Posted: Wednesday 11 March 2009 09:44 p.m. by rcook (279 words) Edit | Delete | Compose post…