Intention revealing method is simple and yet I see it frequently slip through programmers' code. Developers don't like lengthy methods, or find it inconvenient to read through chubby if-else branches, and if they are nice enough they'll leave comments like those.
If we change spaces by underscores in the comments, delete the comment characters, and define the resulting methods in the same file (as private helpers for example), we get code that explains itself, instead of through verbose long methods, or human code comments which get stale.
Intention revealing methods is the most basic, no brain-teaser, easiest rule that I know. Combine it with Sandi Metz's rule of a maximum of 5 lines per method and you'll get simple code that explains itself, that is a pleasure to read, improving communication and productivity of the team (even when it's only yourself).
if current_user && current_user.admitted_at < 1.week.ago
# When user is admitted at least a week ago we show it's active projects and
# admitted-only ones
@active_projects = current_user.projects.active
@promo_projects = Project.promo
else
# If not admitted we show some featured projects, and set a marketing flash
# message when user is new
if current_user && current_user.created_at > 1.week.ago
flash[:info] = 'Sign up for having your own projects, and see promo ones!'
end
@featured_projects = Project.active.featured
end
if user_already_admitted?
set_user_projects
else
set_featured_projects
upsell_if_new_user
end
private
def set_user_projects
@active_projects = current_user.projects.active
@promo_projects = Project.promo
end
def set_featured_projects
@featured_projects = Project.active.featured
end
def upsell_if_new_user
return if current_user.nil?
if current_user.created_at > 1.week.ago
flash[:info] = 'Sign up for having your own projects, and see promo ones!'
end
end
def user_already_admitted?
return false if current_user.nil?
current_user.admitted_at < 1.week.ago
end
Having semantic names instead of code also helps to spot when we work at different levels of abstraction in the same place, unveiling next steps in improving the code structure.
http://ntcoding.blogspot.com.ar/2011/05/clean-code-tricks-intention-revealing.html http://www.codinghorror.com/blog/2008/07/coding-without-comments.html
problem solved! (joke).
looking forward to this one.