back

Refactorings

Programing is about creating abstractions and concepts that model behavior in the real world so that a computer can understand it. In this translation we forget that machines read binary code, but humans are the onces reading the source code of a program. This is a small refactoring showing how you can abstract meaning from a simple if statement so that our coworkers and ourself can better comprehend the code at hand when we read it in the future.

BEFORE

def index
  if (session[:account] != nil) && (session[:venue] == nil or session[:venue] == 0)
    @cached = CachedEvent.find_by_accounts_ids( session[:account], @date_range).to_a
  elsif (session[:venue] != nil) && (session[:venue] != 0)
    @cached = CachedEvent.find_by_venues_ids( session[:venue], @date_range).to_a
  else
    render :action => "select_account" if session[:account] == nil
  end
end

AFTER

Take a closer look at the IF statement. We can clearly comprehend what is happening there. I know, I can still be improve, but for now the code is in better shape.

def index
  if have_account_but_not_venue
    @cached = CachedEvent.find_by_accounts_ids( session[:account], @date_range).to_a
  elsif have_venue_selected
    @cached = CachedEvent.find_by_venues_ids( session[:venue], @date_range).to_a
  else
    render :action => "select_account" if session[:account] == nil
  end
end

def have_account_but_not_venue
  (session[:account] != nil) && (session[:venue] == nil or session[:venue] == 0)
end

def have_venue_selected
  (session[:venue] != nil) && (session[:venue] != 0)
end

blog comments powered by Disqus