Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I need help cleaning up this piece of code.

if is_complete == true
  #If there are time stamps get between time stamps
  if start_date && end_date
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
  else
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL", contact_id])
  end
else
  #If there are time stamps get between time stamps
  if start_date && end_date
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
  else
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL", contact_id])
  end
end
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted
  1. you can replace if is_complete == true with if is_complete
  2. the only thing that changes is :conditions, tasks = ... should not be inside the if/else
  3. the 3rd case is invalid: completed_date can't be NULL and within a certain range at the same time
  4. use one conditional for the NOT in completed_date IS (NOT) NULL and one for the and DATE ..., and concatenate the sql string then. Then the nested if/else is gone.
  5. the extra query arguments start_date and end_date depend only on start_date && end_date, so the distinctions should not be in the is_completed conditional.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.