refactoring_improving_the_design_of_existing_code

Page 143

} public String getCustomer() { return _customer; } public void setCustomer(String arg) { _customer = arg; } private String _customer; Some client code that uses this looks like

private static int numberOfOrdersFor(Collection orders, String customer) { int result = 0; Iterator iter = orders.iterator(); while (iter.hasNext()) { Order each = (Order) iter.next(); if (each.getCustomerName().equals(customer)) result++; } return result; } First I create the new customer class. I give it a final field for a string attribute, because that is what the order currently uses. I call it name, because that seems to be what the string is used for. I also add a getting method and provide a constructor that uses the attribute:

class Customer { public Customer (String name) { _name = name; } public String getName() { return _name; } private final String _name; } Now I change the type of the customer field and change methods that reference it to use the appropriate references on the customer class. The getter and constructor are obvious. For the setter I create a new customer:

class Order... public Order (String customer) { _customer = new Customer(customer); } public String getCustomer() { return _customer.getName(); } private Customer _customer; public void setCustomer(String arg) { _customer = new Customer(customer); }

143


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.