From: Philip Mak Date: 2002-09-23T03:36:42+09:00 Subject: Re: The problem with run-time type checking Dossy wrote: > > Then again, doing (2) seems to add a significant amount of extra code > > I have to write. In typed languages, I just need to specify what type > > a variable should be; not have to write a whole line to raise an > > exception if the variable isn't the right type. > > > > Does anyone have a better idea? > > Automated unit tests. You get test coverage and peace of mind with > dynamically typed languages at the same time. How do automated unit tests help with this? I can't figure it out. A function like this: def escapeHTML(string) string.gsub(/&/n, '&').gsub(/\"/n, '"').gsub(/>/n, '>').gsub(/ The beauty of Ruby (and OO in general) is being able to make "objects" > ... what if you wanted to pass in your own object that wasn't inherited > from String (and thus, is not a #kind_of? String) but implements the > #gsub method? > > Even testing using #respond_to? isn't foolproof because of > #method_missing ... I could think of doing this, which would only raise an exception if the given object doesn't implement the #gsub method even using #method_missing: def escapeHTML(string) begin return gsub(...) rescue NameError raise TypeError, "string must be String, not #{string.class}" end end Still, I think it's too tedious to be doing that sort of thing on just about every function that accepts parameters that I write... and the escapeHTML() example is already a relatively trivial one. Thoughts?