Todd,
Sorry for misunderstanding. I was just saying that, while you can or should use exceptions in your own code, you should try to provide 'error-free' API to external programmers, by trapping all problems and documenting the rules and error conventions of your interface.
In your example Challenge #2, I just notice that this is what you do, since any call to your GetData() method, will never raise an exception!
Fredo
PS: I have two small remarks about your code sample, for the Integer?() method:
Not a good habit to extend Ruby built-in class. Just imagine I do the same (knowing that the name "integer?" is quite natural) and override your code by mine. Better have a neutral method like Fredo6.Integer?(), so that at least you and me control ownership.
I would rather use the following code to transform a string into an integer:
def string_to_integer(s)
(s && s.strip =~ /\A(\+|\-|\s*)(\s*)(\d*)\Z/) ? ($1.strip + $3).to_i ; nil
end
This returns the integer number if the string is valid, otherwise nil
A more powerful variant allows the user entering mathematical expressions that would normally evaluate to an integer
def string_to_integer2(s)
return nil if s == nil || s =~ /[^\s\+\-\*\/\%(\)\d]/
begin
eval "(#{s}) + 0"
rescue Exception => detail
nil
end
end
For instance, string_to_integer2("(2 + 3) * 4") will return 20. The only issue with eval() is with security, as eval() could be used to delete files on your disk and other nasty things by accident. Hence, the first line to check that you only have digits with operation signs and parentheses.
Fredo