C# 代码质量优化指南

本文将通过多个编程技巧和实践,展示如何显著改善代码质量。以 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老胖闲聊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值