Refactoring: Refactorings/Move Field
Jump to navigation
Jump to search
If a field is (or will be) used by another class more frequently than the class in which it is defined, then it should be a field of that class.
Mechanics
- If you are likely to be moving the methods that access the field frequently or if a lot of methods access the field, it might be better to use Self Encapsulate Field
- Test
- Create an attribute reader and a writer (if necessary) in the target class.
- Determine how to reference the target object from the source
- Note: If an existing field does not already give the target, create a method that will do so. If that still doesn't work, create a new field in the source that can store the target. Try to refactor until this can potentially be removed
- Replace all references to the source field with references to the appropriate method on the target. Also look in subclasses
- Test
Example
Before
class Account
def interest_for_amount_days(amount, days)
@interest_rate * amount * days / 365
end
end
class AccountType
# ...
end
After
class AccountType
attr_accessor :interest_rate
end
class Account
def interest_for_amount_days(amount, days)
@account_type.interest_rate * amount * days / 365
end
end