开发者

Safely call methods

Is there a nice way how to write:

a = one.two.three.four

where "one" - assigned, "two" - nil. This statement makes an 开发者_JAVA技巧exception.

I want to have "a" nil if any of "two", "three", "four" are nil, otherwise to have result of "four" in "a".

Is it possible to do this without writing condition statements?


First of all, you need to find out if this code violates the Law of Demeter. If that is the case, then the correct solution to this problem is to not write code this way.

How would you find out if its breaking it? Here is one article that tries to explain how that applies to Ruby language.

In your case, you would break it down into multiple calls, with guard clauses around it. In the call one.two.three.four, we can assume that four is a property of three (rather, the object returned by three). And three would be a property of two. So you would add a method in two:

# Note: This is an over-simplified example
def three_four
  return unless three
  three.four
end

And in one you would have:

def two_three_four
  return unless two
  two.three_four
end

A more relevant example:

invoice.customer.primary_address.zipcode

So you would have Customer#primary_address_zipcode and Invoice#customer_primary_address_zip_code (Or a better abbreviated name, that would make more sense)


a = one.try(:two).try(:three).try(:four)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜