本文将通过多个编程技巧和实践,展示如何显著改善代码质量。以 C# 为例,结合 卫语句、枚举、字典映射、单一职责原则 等技巧,逐步优化代码。
1. 卫语句(Guard Clause)
卫语句用于提前处理特殊情况,避免深层嵌套的条件判断,使代码逻辑更清晰。
传统嵌套写法
public string ProcessOrder(int quantity, double price, double discount)
{
if (quantity > 0)
{
if (price > 0)
{
if (discount >= 0)
{
double total = quantity * price * (1 - discount);
return $"Total cost: {
total}";
}
else
{
return "Discount must be non-negative";
}
}
else
{
return "Price must be positive";
}
}
else
{
return "Quantity must be positive";
}
}
使用卫语句改进
public string ProcessOrder(int quantity, double price, double discount)
{
// 卫语句:提前检查特殊情况
if (quantity <= 0)
return "Quantity must be positive";
if (price <= 0)
return "Price must be positive";
if (discount < 0)
return "Discount must be non-negative";
// 主逻辑:无需嵌套
double total = quantity * price * (1 - discount);
return $"Total cost: {
total}";
}
优点:
- 减少嵌套层次,代码更易读。
- 提前处理异常情况,逻辑更清晰。
2. 使用枚举替换嵌套条件
枚举可以用来替换某些场景下的嵌套条件判断,尤其是当代码中存在多个固定的状态或类型时。
传统嵌套写法
public string GetPermissionLevel(string role)
{
if (role == "admin")
{
return "Full access";
}
else if (role == "editor")
{
return "Edit access";
}
else if (role == "viewer")
{
return "View access";
}
else
{
return "No access";
}
}
使用枚举改进
public enum Role