开发者

DRY - Multiple lines of code performing the same update function

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?


A simple helper will cut down on the noise:

def update_records!
    update_one(event_home_team)
    update_one(event_away_team)
    update_one(event_home_team_division)
    update_one(event_away_team_division) unless event_away_team_division == event_home_team_division
    update_one(user)
end

private

def update_one(team)
    PoolRecord.for_recordable_and_user(team, user).update_for!(self)
end

And if for some reason you want to take it another step you could do something like this:

def update_records!
    [
        [ event_home_team,          true ],
        [ event_away_team,          true ],
        [ event_home_team_division, true ]
        [ event_away_team_division, event_away_team_division != event_home_team_division ],
        [ user,                     true ]
    ].each do |team, do_it|
        if(do_it)
            PoolRecord.for_recordable_and_user(team, user).update_for!(self)
        end
    end
end

Or, depending on your data, this might work:

def update_records!
    [
        event_home_team, 
        event_away_team,
        event_home_team_division, 
        event_away_team_division,  
        user
    ].uniq.each do |team|
        PoolRecord.for_recordable_and_user(team, user).update_for!(self)
    end
end

This last one replaces the single unless a == b condition in your original with a simple uniq 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜