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);
        }
    }
  • 相关阅读:
    最小顶点覆盖,最大独立集,最小边覆盖
    Security Badges
    异常
    List和Set
    数据结构
    Collection集合
    Excel序号递增
    VM虚拟机桥接模式无法联网解决办法
    mybatis-Plus方法指定更新的字段
    maven项目 导出相关依赖包到指定文件夹
  • 原文地址:https://www.cnblogs.com/Evelia/p/3494118.html
Copyright © 2011-2022 走看看