Refactoring: Refactorings/Change Reference to Value
Jump to navigation
Jump to search
A reference object can become small, immutable, and awkward to manage.
Mechanics
- Check that the candidate object is immutable or can become immutable (Try using Remove Setting Method). If not, abandon this refactoring.
- Create an == method and an eql? method (eql? can delegate to ==)
- Create a hash method
- Test
- Consider removing factory method and making a public constructor.
Example
Before
class Currency
attr_reader :code
def initialize(code)
@code = code
end
def self.get(code)
# return currency from registry
end
end
# usage
usd = Currency.get("USD")
Currency.new("USD") == Currency.new("USD") # returns false
After
class Currency
attr_reader :code
def initialize(code)
@code = code
end
def self.get(code)
# return currency from registry
end
def eql?(other)
self == (other)
end
def ==(other)
other.equal?(self) || (other.instance_of?(self.class) && other.code == code)
end
def hash
code.hash
end
end
# usage
Currency.send(:new, "USD") == Currency.new("USD") # returns true