Be lazy and don’t keep context in your head

Sometimes, code we read makes us to remember context. Consider the following code (it sends an invite email to a user):

def process_invitation(invitation)
if user = User.find_by(email: invitation['email'])
unless user.belongs_to_team?(@team.id)
membership = add_membership(user, invitation['role'])
send_mail(membership.id, user: false)
end
return
end
user = User.new(user_data(invitation['email']))
unless user.save
Rails.logger.info \
'Notify inviter that the user could not be invited for a reason'
return
end
user.add_to_default_team unless @team.hide_default_team?
membership = add_membership(user, invitation['role'])
user.switch_team @team.id
user.save!
send_mail(membership.id, user: true)
end

Lines 2-8 (see above ↑) deal with the case of existing user, and the rest deal with the case of new user.

When reading lines 3-5 you have to remember that you're dealing with an existing user, same with lines 12-22, only there you deal with a new user. After all, both existing user and new user cases use same variable name: user.

But there's a better way than keeping it in your head. Keeping it in the code:

def process_invitation(invitation)
if existing_user = User.find_by(email: invitation['email'])
unless existing_user.belongs_to_team?(@team.id)
membership = add_membership(existing_user, invitation['role'])
send_mail(membership.id, new_user: false)
end
return
end
new_user = User.new(user_data(invitation['email']))
unless new_user.save
Rails.logger.info \
'Notify inviter that the user could not be invited for a reason'
return
end
new_user.add_to_default_team unless @team.hide_default_team?
membership = add_membership(new_user, invitation['role'])
new_user.switch_team @team.id
new_user.save!
send_mail(membership.id, new_user: true)
end

Reading lines 3-5 (see above ↑), you clearly see that you're dealing with an existing user. And same for the lines dealing with a new user.

Happy hacking!

Fed up working on bad code? Here's a way out!

For people that that want to stop suffering from bad code I’ve made a FREE course

Web Analytics