Refactoring: Refactorings/Change Value to Reference
Jump to navigation
Jump to search
A data object can sometimes accumulate many identical instances. These identical instances should be replaced with references to a single, unique object.
Mechanics
- Use Replace Constructor with Factory Method
- Test
- Decide what object is responsible for providing access to the objects (maybe one or more hashes or registry objects)
- Decide whether objects are already created (in which case they need to be retrieved from memory) or created on the fly.
- Alter the factory method to return the reference object.
- Test
Example
Before
class Customer
attr_reader :name
def initialize(name)
@name = name
end
end
class Order
def initialize(customer_name)
@customer = Customer.new(customer_name)
end
def customer=(customer_name)
@customer = Customer.new(customer_name)
end
def customer_name
@customer.name
end
end
# usage
def self.number_of_orders_for(orders, customer)
orders.select { |order| order.customer_name == customer.name }.size
end
After
class Customer
attr_reader :name
Instances = {}
def initialize(name)
@name = name
end
def self.with_name(name)
Instances[name]
end
def self.load_customers
new("Lemon Car Hire").store
new("Associated Coffee Machines").store
new("Bilston Gasworks").store
end
def store
Instances[name] = self
end
end
class Order
def initialize(customer_name)
@customer = Customer.with_name(customer_name)
end
def customer=(customer_name)
@customer = Customer.with_name(customer_name)
end
def customer_name
@customer.name
end
end