Refactoring: Refactorings/Self Encapsulate Field
Jump to navigation
Jump to search
Instead of accessing class instance variables directly, create an accessor (getter and setter) method to manipulate the variable.
Mechanics
- Create a getting and setting method for the field
- Find all references to the field and replace them with a getting or setting method
- Double check that you have caught all references
- Test
Example
Before
class Item
def initialize(base_price, tax_rate)
@base_price, @tax_rate = base_price, tax_rate
end
def raise_base_price_by(percent)
@base_price = @base_price * (1 + percent/100.0)
end
def total
@base_price * (1 + @tax_rate)
end
end
After
class Item
attr_accessor :base_price, :tax_rate
def initialize(base_price, tax_rate)
setup(base_price, tax_rate)
end
def setup(base_price, tax_rite)
@base_price, @tax_rate = base_price, tax_rate
end
def raise_base_price_by(percent)
base_price = base_price * (1 + percent/100.0)
end
def total
base_price * (1 + tax_rate)
end
end