减少if-else使用

本文介绍如何通过重构简化复杂的if-else语句,包括减少嵌套、使用映射表替代多个条件判断等技巧,提高代码可读性和维护性。

删除 else

如:

function test($arg)
{
    if($arg == 'foobar'){
        return true;
    }else{
        return false;
    }
}

尽量写成这样

function test($arg)
{
    if($arg == 'foobar'){
        return true;
    }

    return false;
}

优先将代码量少,可使流程中断的代码块(return, throw excetion, continue ...)放到 if 中, 提前中断代码。


罗列规则式的写代码

多层 if 嵌套的语法,把他写成线性的,就像写规则一样将其一条条罗列出来

如:

function match($age, $salary, $pretty){
    if($age > 18){
         // do some thing A;
        if($salary > 5000){
            // do some thing B;
            if($pretty == true){
                return true;
            }
        }
    }

    return false;
}

改写成这样是不是清晰多了?

function match($age, $salary, $pretty){
    if($age < 18){
        return false;
    }

    // do some thing A;

    if($salary < 5000){
        return false;
    }

    // do some thing B;

    return $pretty == true;
}


function contry_initial($country){
    if ($country==="China" ){
       return "CHN";
    }else if($country==="America"){
       return "USA";
    }else if($country==="Japna"){
      return "JPN";
    }else{
       return "OTHER";
    }
}

这样的if语句,可以看到值和返回是一一对应的,所以你可以这样写

function contry_initial($country){
  $countryList=[
      "China"=> "CHN",
      "America"=> "USA",
      "Japna"=> "JPN",
    ];

    if(in_array($country, array_keys($countryList))) {
        return $countryList[$country];
    }
    return "Other";

}

如果需要更加自由的定义映射表的话,可以这样写

function contry_initial($country, array $countryList){
    if(in_array($country, array_keys($countryList))) {
        return $countryList[$country];
    }
    return "Other";
}

完全去掉if语句可以写成

function contry_initial($country, array $countryList){
    return in_array($country, array_keys($countryList))?$countryList[$country]:"Other";
}



https://laravel-china.org/topics/1284/if-else-reconstruction-experience
https://laravel-china.org/topics/1263/tips-to-make-your-if-else-look-more-beautiful
在C#编程中减少 `if-else` 语句的使用,不仅可以提升代码的可读性,还能增强代码的可维护性。以下是一些常用的技术和实践方法,适用于不同场景下的条件逻辑重构。 ### 使用枚举与接口实现策略模式 通过定义接口和实现类,可以将不同的行为封装到不同的类中,从而避免使用大量的 `if-else` 语句来判断行为类型。这种模式被称为策略模式。例如,可以定义一个接口 `IAction`,然后为每种行为创建一个实现类: ```csharp public interface IAction { void Execute(); } public class ActionA : IAction { public void Execute() { Console.WriteLine("执行动作A"); } } public class ActionB : IAction { public void Execute() { Console.WriteLine("执行动作B"); } } ``` 在使用时,可以通过一个工厂方法或字典来映射不同的行为类型到具体的实现类: ```csharp Dictionary<string, IAction> actions = new Dictionary<string, IAction> { { "A", new ActionA() }, { "B", new ActionB() } }; string actionType = "A"; if (actions.TryGetValue(actionType, out IAction action)) { action.Execute(); } else { Console.WriteLine("未知的动作类型"); } ``` ### 使用 `switch` 表达式(C# 8.0 及以上) 从 C# 8.0 开始,`switch` 表达式提供了一种更简洁的方式来处理多条件分支。它允许返回值,并且语法更加简洁: ```csharp string result = actionType switch { "A" => "执行动作A", "B" => "执行动作B", _ => "未知的动作类型" }; Console.WriteLine(result); ``` ### 使用字典映射函数 对于简单的条件判断,可以使用字典将条件映射到对应的函数或委托。这种方式特别适合于条件较少且逻辑简单的情况: ```csharp Func<string> actionA = () => "执行动作A"; Func<string> actionB = () => "执行动作B"; Dictionary<string, Func<string>> actionMap = new Dictionary<string, Func<string>> { { "A", actionA }, { "B", actionB } }; string actionType = "A"; if (actionMap.TryGetValue(actionType, out Func<string> action)) { Console.WriteLine(action()); } else { Console.WriteLine("未知的动作类型"); } ``` ### 使用多态 多态是面向对象编程中的一个重要特性,它允许使用基类或接口来表示不同的派生类实例。通过多态,可以在不修改调用代码的情况下扩展新的行为类型: ```csharp public abstract class Animal { public abstract void Eat(); } public class Dog : Animal { public override void Eat() { Console.WriteLine("吃骨头"); } } public class Cat : Animal { public override void Eat() { Console.WriteLine("吃鱼"); } } // 使用时 Animal animal = new Dog(); animal.Eat(); // 输出:吃骨头 ``` ### 使用模式匹配(C# 7.0 及以上) C# 7.0 引入了模式匹配功能,它允许在 `is` 表达式和 `switch` 语句中使用更复杂的模式匹配逻辑。这可以用于替代复杂的 `if-else` 判断: ```csharp object obj = "Hello"; if (obj is string s) { Console.WriteLine($"字符串: {s}"); } else if (obj is int i) { Console.WriteLine($"整数: {i}"); } else { Console.WriteLine("未知类型"); } ``` ### 使用 LINQ 查询 对于某些基于集合的条件筛选,可以使用 LINQ 查询来替代传统的 `if-else` 循环判断。例如,筛选出所有偶数: ```csharp List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 }; var evenNumbers = numbers.Where(n => n % 2 == 0); foreach (int number in evenNumbers) { Console.WriteLine(number); } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值