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, '&amp;').gsub(/\"/n, '&quot;').gsub(/>/n, '&gt;').gsub(/</n, '&lt;')
end

if passed e.g. an array, will crash when gsub() can't be called on it. The
problem is that the resulting stack dump is uninformative, requiring the
person calling the function to look at the source code of the function in
order to figure out the problem.

I'm asking when I write a function that depends on its arguments to be a
specific type, how can I make them produce informative stack dumps if the
arguments are the wrong type? I don't see how unit testing would help the
person writing a library function.

> 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?