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);
        }
    }
  • 相关阅读:
    js修改div标签中的内容
    echarts如何显示在页面上
    mybatis提取<where><if>共用代码
    部署LAMP-LAMP平台集成
    PHP安装指南
    部署LAMP-mysql 安装
    apache虚拟主机
    apache默认网站
    HDU 5375 Gray code 格雷码(水题)
    HDU 5371 Hotaru's problem (Manacher,回文串)
  • 原文地址:https://www.cnblogs.com/Evelia/p/3494118.html
Copyright © 2011-2022 走看看