开发者

Am I abusing "rescue" for nil checks?

开发者 https://www.devze.com 2023-01-16 09:38 出处:网络
I use rescue for everything, not just for \"rescuing\" 开发者_如何学Pythonexceptions. I mean, I just love the way it spares me verification and double checking data.

I use rescue for everything, not just for "rescuing" 开发者_如何学Pythonexceptions. 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?


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消