C#代码重构:提升代码质量的五个技巧

开发 前端
代码重构是每个开发者都应该掌握的重要技能。通过重构,我们可以在不改变代码外部行为的前提下,优化代码结构,提高可读性和可维护性。本文将介绍5个强大的C#重构技巧,帮助您将代码提升到一个新的水平。

代码重构是每个开发者都应该掌握的重要技能。通过重构,我们可以在不改变代码外部行为的前提下,优化代码结构,提高可读性和可维护性。本文将介绍5个强大的C#重构技巧,帮助您将代码提升到一个新的水平。

1. 提取验证逻辑

将分散的验证逻辑提取到单独的方法中,可以显著提高代码的可读性和可维护性。

重构前:

public void AddCustomer(string firstName, string lastName, string email, DateTime dateOfBirth)
{
    if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName))
    {
        throw new ArgumentException("First name and last name are required.");
    }


    if (!email.Contains('@') && !email.Contains('.'))
    {
        throw new ArgumentException("Invalid email format.");
    }


    if (CalculateAge(dateOfBirth, DateTime.Now) < 21)
    {
        throw new ArgumentException("Customer must be at least 21 years old.");
    }


    // 添加客户的其他逻辑
}

重构后:

public void AddCustomer(string firstName, string lastName, string email, DateTime dateOfBirth)
{
    if (!IsValid(firstName, lastName, email, dateOfBirth))
    {
        throw new ArgumentException("Invalid customer data.");
    }


    // 添加客户的其他逻辑
}


private bool IsValid(string firstName, string lastName, string email, DateTime dateOfBirth)
{
    const int minimumAge = 21;
    return !string.IsNullOrEmpty(firstName) &&
           !string.IsNullOrEmpty(lastName) &&
           (email.Contains('@') || email.Contains('.')) &&
           CalculateAge(dateOfBirth, DateTime.Now) >= minimumAge;
}

2. 引入依赖注入

依赖注入(DI)是一种强大的设计模式,可以提高代码的模块化、可测试性和可扩展性。

重构前:

public class CustomerService
{
    private CompanyRepository _companyRepository = new CompanyRepository();
    private CustomerRepository _customerRepository = new CustomerRepository();
    private CreditLimitCalculator _creditLimitCalculator = new CreditLimitCalculator();


    // 其他方法
}

重构后:

public class CustomerService
{
    private readonly CompanyRepository _companyRepository;
    private readonly CustomerRepository _customerRepository;
    private readonly CreditLimitCalculator _creditLimitCalculator;


    public CustomerService(CompanyRepository companyRepository, 
                           CustomerRepository customerRepository, 
                           CreditLimitCalculator creditLimitCalculator)
    {
        _companyRepository = companyRepository;
        _customerRepository = customerRepository;
        _creditLimitCalculator = creditLimitCalculator;
    }


    // 其他方法
}

3. 使用switch表达式简化复杂业务规则

对于复杂的业务规则,使用switch表达式可以使代码更加简洁和易读。

重构前:

public (bool HasCreditLimit, decimal? CreditLimit) CalculateCreditLimit(Customer customer, Company company)
{
    if (company.Type == CompanyType.VeryImportantClient)
    {
        return (false, null);
    }
    else if (company.Type == CompanyType.ImportantClient)
    {
        return (true, GetCreditLimit(customer) * 2);
    }
    else
    {
        return (true, GetCreditLimit(customer));
    }
}

重构后:

public enum CompanyType
{
    VeryImportantClient,
    ImportantClient,
    RegularClient
}


public class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
    // Other properties
}


public class Company
{
    public string Name { get; set; }
    public CompanyType Type { get; set; }
    // Other properties
}




public class CreditLimitCalculator
{
    public (bool HasCreditLimit, decimal? CreditLimit) CalculateCreditLimit(Customer customer, Company company)
    {
        return company.Type switch
        {
            CompanyType.VeryImportantClient => (false, null),
            CompanyType.ImportantClient => (true, GetCreditLimit(customer) * 2),
            _ => (true, GetCreditLimit(customer))
        };
    }


    private decimal GetCreditLimit(Customer customer)
    {
            return 1000m;
    }
}




static void Main(string[] args)
{
    var customer = new Customer { Name = "John Doe", Age = 30 };
    var company1 = new Company { Name = "Acme Corp", Type = CompanyType.RegularClient };
    var company2 = new Company { Name = "Important Inc", Type = CompanyType.ImportantClient };
    var company3 = new Company { Name = "VIP Ltd", Type = CompanyType.VeryImportantClient };


    var calculator = new CreditLimitCalculator();


    var result1 = calculator.CalculateCreditLimit(customer, company1);
    Console.WriteLine($"Company: {company1.Name}, HasCreditLimit: {result1.HasCreditLimit}, CreditLimit: {result1.CreditLimit}");


    var result2 = calculator.CalculateCreditLimit(customer, company2);
    Console.WriteLine($"Company: {company2.Name}, HasCreditLimit: {result2.HasCreditLimit}, CreditLimit: {result2.CreditLimit}");


    var result3 = calculator.CalculateCreditLimit(customer, company3);
    Console.WriteLine($"Company: {company3.Name}, HasCreditLimit: {result3.HasCreditLimit}, CreditLimit: {result3.CreditLimit}");
}

图片图片

4. 将逻辑下推到领域模型

通过将逻辑下推到领域模型,我们可以提高代码的内聚性和封装性。

重构前:

public class CustomerService
{
    public Customer CreateCustomer(Company company, string firstName, string lastName, string email, DateTime dateOfBirth)
    {
        // 创建客户的逻辑
    }


    public bool IsCustomerUnderCreditLimit(Customer customer)
    {
        return customer.HasCreditLimit && customer.CreditLimit < 500;
    }
}

重构后:

public class Customer
{
    public static Customer Create(Company company, string firstName, string lastName, string email, DateTime dateOfBirth, CreditLimitCalculator creditLimitCalculator)
    {
        // 工厂方法实现
    }


    public bool IsUnderCreditLimit()
    {
        return HasCreditLimit && CreditLimit < 500;
    }
}

5. 使用表达式体成员简化简单方法

对于简单的方法,使用表达式体成员可以使代码更加简洁。

重构前:

public class Customer
{
    public string FullName
    {
        get
        {
            return $"{FirstName} {LastName}";
        }
    }


    public bool IsAdult()
    {
        return Age >= 18;
    }
}

重构后:

public class Customer
{
    public string FullName => $"{FirstName} {LastName}";


    public bool IsAdult() => Age >= 18;
}

通过应用这些重构技巧,您可以显著提高C#代码的质量、可读性和可维护性。记住,重构是一个持续的过程,随着您的技能不断提升,您的代码质量也会不断提高。祝您编码愉快!

责任编辑:武晓燕 来源: 技术老小子
相关推荐

2014-02-04 19:48:07

重构代码质量

2022-03-25 09:22:42

代码开发

2020-07-15 14:51:39

代码C+开发

2021-12-29 11:06:25

Java代码技巧

2015-08-11 09:39:25

重构提高代码质量

2024-11-18 19:00:29

2017-10-30 15:22:29

代码可读性技巧

2024-09-29 10:35:43

2019-11-05 08:34:33

代码switch开发

2024-04-26 11:14:34

C#单元测试框架

2023-02-06 12:00:00

重构PythonPythonic

2023-01-11 11:35:40

重构PythonPythonic

2023-09-26 12:04:15

重构技巧Pythonic

2017-01-20 09:45:20

JavaScript代码质量

2024-11-01 07:30:00

2011-08-16 09:47:58

编程

2024-10-09 12:18:38

2021-10-14 07:55:17

提示技巧C#

2010-08-10 09:51:19

C#代码

2010-05-20 09:07:30

jQuery
点赞
收藏

51CTO技术栈公众号