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);
        }
    }
  • 相关阅读:
    1641. 统计字典序元音字符串的数目
    1688. 比赛中的配对次数
    核心思路
    面试题 16.17. 连续数列
    70. 爬楼梯
    面试题 08.01. 三步问题
    剑指Offer 42. 连续子数组的最大和
    设计模式之原型模式
    代理模式之动态代理
    设计模式之禅(六大设计原则)
  • 原文地址:https://www.cnblogs.com/Evelia/p/3494118.html
Copyright © 2011-2022 走看看