处理 nil 对象和属性的最佳实践是什么? [英] What is the best practice for handling nil objects and properties?

查看:45
本文介绍了处理 nil 对象和属性的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 User 对象,它有一个 email 属性,我需要他们的 email 的大写最后一个字母:

Say I have a User object, which has an email property, and I need the upper cased last letter of their email:

u = User.find(1)    
letter = u.email.upcase.last

如果 uemail 在这个链中是 nil,那么我得到一个 NoMethodError: undefined method 'blah' for nil:Nilclass.在大多数情况下,我应该能够解决它,但有时, nil 会到达它不应该或难以包含的地方.一种方式是冗长的:

If u or email is nil in this chain, then I get a NoMethodError: undefined method 'blah' for nil:Nilclass. I should be able to work around it in most cases, but sometimes, a nil gets where it shouldn't or its hard to contain. One way would be verbose:

u = User.find(1)
letter = nil
if u && u.email
 letter = u.email.upcase.last
end

但这在视图中或在a.bunch.of.properties.down.a.hierarchy 的长链中会变得烦人和危险.我阅读了 Rails 中的 try 方法:

But this gets annoying and hazardous in a view, or in a long chain of a.bunch.of.properties.down.a.hierarchy. I read about try method in Rails:

u = User.find(1)
letter = u.try(:email).try(:upcase).try(:last)

这不那么冗长,但我觉得写所有这些尝试都很讨厌.一旦我将 try 放入链中,我就必须一直使用它们.有没有更好的办法?

This is less verbose, but I feel icky writing all those tries. And once I put try in the chain, I have to use them all the way down. Is there a better way?

推荐答案

我喜欢使用 空对象模式.Avdi 有一篇很好的帖子解释了这一点,但是基本思想是你有一个小类可以代表一个对象并合理地响应你可能传递原始对象的消息.我发现这些不仅对于避免 NoMethodError 很有用,而且对于设置默认值/好的消息也很有用.

I like to use the Null Object Pattern. Avdi has a great post explaining this, but the basic idea is you have a little class that can stand in for an object and respond reasonably to the messages you might pass the original object. I've found these are useful not only for avoiding NoMethodErrors but also for setting default values/nice messages.

例如,你可以这样做:

class NilUser
  def email
    "(no email address)"
  end
end

u = User.find(1) || NilUser.new
u.email.upcase.last # => No errors!

这篇关于处理 nil 对象和属性的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆