Refactoring: Refactorings/Extract Class
Jump to navigation
Jump to search
Classes should have crisp abstraction and a few clear responsibilities. When the classes get too big and complicated, you should create a new class to handle the extra responsibilities.
Mechanics
- Decide how to split the responsibilities of the class
- Create a new class to express the split-off responsibilities. Rename the old class to better describe if necessary
- Make a link from the old to the new class (might need a back link, but not unless absolutely necessary)
- Use Move Field on each field you want to move
- Test after each move
- Use Move Method to move methods from old to new class. Start with low-level methods (called rather than calling) and build to higher level.
- Test after each move
- Review and reduce interfaces of each class (try to remove back link if possible)
Example
Before
class Person
attr_reader :name
attr_accessor :office_area_code, :office_number
def telephone_number
'(' + @office_area_code + ') ' + @office_number
end
# ...
end
After
class Person
attr_reader :name
def initialize
@office_telephone = TelephoneNumber.new
end
def telephone_number
@office_telephone.telephone_number
end
def office_telephone
@office_telephone
end
end
class TelephoneNumber
attr_accessor :area_code, :number
def telephone_number
'(' + area_code + ') ' + number
end
end