On Wed, Jan 13, 2010 at 12:11 AM, R. Kumar <sentinel.2001 / gmx.com> wrote:
> Albert Schlef wrote:
>> It'd be faster if you use the 'alias' keyword instead of wrapping the
>> call in a function of your own because then you save one function call.
>
> Thanks a lot for your answer. This brings up a question on usage of
> "rescue". Is it a "code smell" or bad programming?

"Code smell" is a weak concept that people use when they can't give
clear, concise reasons why they don't like something about a piece of
code.

There is nothing wrong with "rescue".  It's an essential part of
writing good code, in fact.  That doesn't mean it can't be misused,
though.

> I recall i've used it in some places where often different datatypes can
> come in. Forgetting this, over time , I've added a ".length()" check or
> ".trim()", "chomp()" etc.

You can use a respond_to? check in your code to see if you are dealing
with an object that supplies the methods you are expecting. This is
often more useful than just calling a method and rescuing its failure.

Also, one thing to be aware of is that while a rescue clause itself
confers only a modest overhead, if you are actually triggering
exceptions that are rescued often, that confers a substantial
overhead.  There are some time consuming things, such as constructing
the backtrace, that go into exceptions, so the fewer exceptions your
code raises, the better, generally.

> Suddenly, when boolean data or Fixnum comes these lines fail, so I tend
> to add a rescue clause. And these are typically in a loop.
> Currently, the "rescue" would work for various cases and datatypes. If I
> open classes and start adding aliases or methods, I could have to do it
> over and over again.

There isn't a clear, well defined answer to this.  It really depends
on the architecture of your overall code.  I would suggest, though,
that if you end up having a lot of lines with rescue clauses at the
end of them, you are probably doing something wrong and need to step
back and look at how you can adjust your code to consolidate the
places where you employ rescue clauses, whether that's by making your
code smarter elsewhere, or by using the begin/rescue/end(else) syntax
to apply a single rescue clause to a broader swath of code.


Kirk Haines