代码重构是每个开发者都应该掌握的重要技能。通过重构,我们可以在不改变代码外部行为的前提下,优化代码结构,提高可读性和可维护性。本文将介绍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#代码的质量、可读性和可维护性。记住,重构是一个持续的过程,随着您的技能不断提升,您的代码质量也会不断提高。祝您编码愉快!