zoukankan      html  css  js  c++  java
  • 典型重构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);
        }
    }
  • 相关阅读:
    get post 小结
    ddt 实例
    通俗大白话来理解TCP协议的三次握手和四次断开
    find xss
    use . adb . get wifi
    http bass
    mac 配置homebrew
    id 与 void * 转换
    Maven
    percent-encode 百分号编码
  • 原文地址:https://www.cnblogs.com/Evelia/p/3494118.html
Copyright © 2011-2022 走看看