DRY - 多行代码执行相同的更新功能
这是我的代码的一个简短示例:
def update_records!
# Teams.
home_team_record = PoolRecord.for_recordable_and_user(event_home_team, user)
home_team_record.update_for!(self)
away_team_record = PoolRecord.for_recordable_and_user(event_away_team, user)
away_team_record.update_for!(self)
# Division(s).
home_team_div_record = PoolRecord.for_recordable_and_user(event_home_team_division, user)
home_team_div_record.update_for!(self)
# Create/update PoolRecord for away_team division if they're in a different division.
unless event_away_team_division == event_home_team_division
away_team_div_record = PoolRecord.for_recordable_and_user(event_away_team_division, user)
away_team_div_record.update_for!(self)
end
# User.
user_record = PoolRecord.for_recordable_and_user(user, user)
user_record.update_for!(self)
end
如果不是需要检查away_team 部门的条件,那么干燥此代码实际上会相当简单。我可以创建一个传入的第一个参数的字符串数组,然后您使用 Object#send。但是,正如我所说,我需要检查一种情况下的条件。您如何建议干燥这个?
Here's a short sample of my code:
def update_records!
# Teams.
home_team_record = PoolRecord.for_recordable_and_user(event_home_team, user)
home_team_record.update_for!(self)
away_team_record = PoolRecord.for_recordable_and_user(event_away_team, user)
away_team_record.update_for!(self)
# Division(s).
home_team_div_record = PoolRecord.for_recordable_and_user(event_home_team_division, user)
home_team_div_record.update_for!(self)
# Create/update PoolRecord for away_team division if they're in a different division.
unless event_away_team_division == event_home_team_division
away_team_div_record = PoolRecord.for_recordable_and_user(event_away_team_division, user)
away_team_div_record.update_for!(self)
end
# User.
user_record = PoolRecord.for_recordable_and_user(user, user)
user_record.update_for!(self)
end
DRY'ing this code would actually be fairly straightforward if it weren't for the condition that needs to be checked for the away_team division. I could create create a string array of the first params passed in and you Object#send. However, like I said, I need to check a condition in one scenario. How would you recommend DRY'ing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个简单的助手将减少噪音:
如果出于某种原因你想采取另一步骤,你可以这样做:
或者,根据你的数据,这可能会起作用:
这最后一个替换了单个
除非使用简单的
条件。uniq
过滤器在原始文件中执行 a == b我不知道您的数据的确切属性,也不知道您想将其发展到什么程度,所以我提供了一些想法。我认为最后一个最接近“说出你的意思”,但也许不是。
A simple helper will cut down on the noise:
And if for some reason you want to take it another step you could do something like this:
Or, depending on your data, this might work:
This last one replaces the single
unless a == b
condition in your original with a simpleuniq
filter.I don't know the exact properties of your data or how far you want to take this so I've offered a few ideas. I think the last one is the closest to "say what you mean" but maybe not.