典型重构3 (Try/Catch)
Try/Catch 块过多
public Customer GetCustomer(string customerId) { try { var command = new SqlCommand(); var reader = command.ExecuteReader(); var customer = new Customer(); while(reader) { customer.customerId=customerId; customer.CustomerName=reader["CustomerName"].ToString(); customer.CustomerStatus=reader["CustomerStatus"].ToString(); customer.LoyaltyProgram=reader["CustomerLoyaltyProgram"].ToString(); } return customer; } catch(Exception ex) { _logger.LogException(ex); var customer=new Customer{CustomerStatus="nuknown"}; return customer; }
将每个代码块中的这些方法析取到外部方法
private static Customer GetCustomerFromDataStore(string customerId) { var command = new SqlCommand(); var reader = command.ExecuteReader(); var customer = new Customer(); while(reader) { customer.customerId=customerId; customer.CustomerName=reader["CustomerName"].ToString(); customer.CustomerStatus=reader["CustomerStatus"].ToString(); customer.LoyaltyProgram=reader["CustomerLoyaltyProgram"].ToString(); } return customer; }
private Customer HandleDataStoreExceptionWhenRetrievingCustomer(Exception ex) { _logger.LogException(ex); var customer=new Customer{CustomerStatus="nuknown"}; return customer; }
重构结果:
public Customer GetCustomer(string customerId) { try { return GetCustomerFromDataStore(customerId); } catch(Exception ex) { return HandleDataStoreExceptionWhenRetrievingCustomer(ex); } }