views:

86

answers:

4

I use rescue for everything, not just for "rescuing" exceptions. I mean, I just love the way it spares me verification and double checking data.

By example, lets say I have a model Item what may or may not have a User. Then, when I want to get the owner's name of the item I write:

item.user.name rescue ""

instead of something like

item.user.nil? ? "" : item.user.name

It makes the same think, since nil.name trigger an exception that I rescue with "", but I'm not pretty sure this is good practice. It makes what I want to, and it makes it with less code, but... I don't know, all that rescue words here and there makes me feel insecure.

Is it a bad practice or is it valid abusing of the rescue keyword?

+1  A: 

Like in most other languages, making the check yourself will run faster than using rescue.

Joshua
+3  A: 

I would say this is not really a good habit to get into. I've never really used this feature in Ruby since it feels like I'm just hiding error cases. It's also worth noting that you're rescuing any and all exceptions without specifying any type of expected error. It's just always looked like something which is going to make debugging down the road harder than it needs to be, although, like I've said, I've never bothered to use it myself.

Pete
+3  A: 

I think you are abusing rescue a bit, though in Rails, there is a specific method for these issues: try. Documentation

In your case, item.user.try(:name) might be a nicer approach.

theIV
Actually, because he said an `item` may or may not have a `user`, I believe he'd need `item.try(:user).try(:name)` :]
j.
I don't believe so. If he has no item, then yes, you're correct. But, if the item may or may not have a user, that's the entire point of using `try`, to catch those situations where `item.user` returns nil instead of a `User`.
theIV
+1  A: 

As an alternative to your rescue abuse, check out the andand gem. It's similiar to the try another posted suggested, but nicer. andand lets you say:

item.user.andand.name

The expression will be nil if item.user is nil.

henning-koch