You are here:   ArielOrtiz.info > S/W Design and Architecture > Refactoring

Refactoring

Note: This is a class activity, nothing needs to be delivered.

Place the following code in the file called student.rb:

# File: student.rb

class Student

  attr_reader :name, :id

  def initialize(name, id, anual_income)
    @name = name
    @id = id
    @anual_income = anual_income
    @grades = []
  end

  def reset_anual_income(anual_income)
    previous_anual_income = @anual_income
    @anual_income = anual_income
    previous_anual_income
  end

  def add_grade(grade)
    @grades << grade
    self
  end

  def meh
    # Display Personal Information
    puts "Name: #{ @name } ID: #{ @id }"
    puts "Anual income: #{ @anual_income }"
    value = 0
    @grades.each do |grade|
      value += grade
    end
    value = value / @grades.size.to_f
    puts "Grade average: #{ value }"

    # Display Disclaimer
    puts 'The contents of this class must not be considered an offer,'
    puts 'proposal, understanding or agreement unless it is confirmed'
    puts 'in a document signed by at least five blood-sucking lawyers.'
  end

  def scholarship_worthy?
    # Nothing reasonable to do if this student has currently no grades. 
    return -1 if @grades.empty?

    # A student is worthy of a scholarship if he/she has good grades and
    # is poor.
    value = 0
    @grades.each do |grade|
      value += grade
    end
    value = value / @grades.size.to_f
    (value >= 85) and (@anual_income < 15_000)
  end

end

In a new file called student_test.rb write a complete unit test class in order to thoroughly verify the current behavior of Student instances.

Afterwards, modify the Student class so that you carry out the following refactorings as many times as you consider necessary:

  1. Replace Magic Number with Symbolic Constant
  2. Rename Method
  3. Split Temporary Variable
  4. Extract Method
  5. Hide Method
  6. Introduce Explaining Variable
  7. Replace Error Code with Exception
  8. Introduce Named Parameter
  9. Separate Query from Modifier
  10. Replace Loop with Collection Closure Method