Refactoring: Refactorings/Replace Data Value with Object
Jump to navigation
Jump to search
Simple data items like strings can become complex to the point where they need behaviors. For example. A telephone field might start out as a simple string, but then needs special formatting behaviors, area code extraction, etc. The best way to fix this is to create an object.
Mechanics
- Create the class for the value. Give it an equivalent to the field in the source class. Add an attribute reader and a constructor that takes the field as an argument.
- Change the attribute reader in the source class to call the reader in the new class.
- If the field is mentioned in the source class constructor, assign the field using the constructor of the new class.
- Change the attribute reader to create a new instance of the new class.
- Test
- You may now need to Change Value to Reference on the new object.
Example
Before
class Order
attr_accessor :customer
def initialize(customer)
@customer = customer
end
end
# Usage
def self.number_of_orders_for(orders, customer)
orders.select{ |order| order.customer == customer}.size
end
After
class Customer
attr_reader :name
def initialize(name)
@name = name
end
end
class Order
def initialize(customer)
@customer = Customer.new(customer)
end
def customer
@customer.name
end
def customer=(value)
@customer = Customer.new(value)
end
end