软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)

一、使用策略模式

1、JS 实例实操
  1. 优化前
js 复制代码
function calculateBonus(employeeType, salary) {
    if (employeeType === "Manager") {
        return salary * 0.2;
    } else if (employeeType === "Developer") {
        return salary * 0.1;
    } else if (employeeType === "Intern") {
        return salary * 0.05;
    } else {
        return 0;
    }
}
  1. 优化后
js 复制代码
const bonusStrategies = {
    Manager: (salary) => salary * 0.2,
    Developer: (salary) => salary * 0.1,
    Intern: (salary) => salary * 0.05,
    default: () => 0,
};

function calculateBonus(employeeType, salary) {
    const strategy = bonusStrategies[employeeType] || bonusStrategies.default;
    return strategy(salary);
}
2、Java 实例实操
  1. 优化前
java 复制代码
public static double calculateBonus(String employeeType, double salary) {
    if ("Manager".equals(employeeType)) {
        return salary * 0.2;
    } else if ("Developer".equals(employeeType)) {
        return salary * 0.1;
    } else if ("Intern".equals(employeeType)) {
        return salary * 0.05;
    } else {
        return 0;
    }
}
  1. 优化后
java 复制代码
interface BonusStrategy {
    double calculate(double salary);
}

public class BonusCalculator {
    private Map<String, BonusStrategy> strategies;

    public BonusCalculator() {
        strategies = new HashMap<>();
        strategies.put("Manager", salary -> salary * 0.2);
        strategies.put("Developer", salary -> salary * 0.1);
        strategies.put("Intern", salary -> salary * 0.05);
    }

    public double calculateBonus(String employeeType, double salary) {
        BonusStrategy strategy = strategies.get(employeeType);
        return strategy != null ? strategy.calculate(salary) : 0;
    }
}

二、使用映射表

1、JS 实例实操
  1. 优化前
js 复制代码
function getDayName(dayNumber) {
    if (dayNumber === 0) return "Sunday";
    else if (dayNumber === 1) return "Monday";
    else if (dayNumber === 2) return "Tuesday";
    else if (dayNumber === 3) return "Wednesday";
    else if (dayNumber === 4) return "Thursday";
    else if (dayNumber === 5) return "Friday";
    else if (dayNumber === 6) return "Saturday";
    else return "Invalid day";
}
  1. 优化后
js 复制代码
const dayNames = {
    0: "Sunday",
    1: "Monday",
    2: "Tuesday",
    3: "Wednesday",
    4: "Thursday",
    5: "Friday",
    6: "Saturday",
};

function getDayName(dayNumber) {
    return dayNames[dayNumber] || "Invalid day";
}
2、Java 实例实操
  1. 优化前
java 复制代码
public static String getDayName(int dayNumber) {
    switch (dayNumber) {
        case 0:
            return "Sunday";
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return "Friday";
        case 6:
            return "Saturday";
        default:
            return "Invalid day";
    }
}
  1. 优化后
java 复制代码
public class DayUtils {
    private static final Map<Integer, String> DAY_NAMES = Map.of(
            0, "Sunday",
            1, "Monday",
            2, "Tuesday",
            3, "Wednesday",
            4, "Thursday",
            5, "Friday",
            6, "Saturday"
    );

    public static String getDayName(int dayNumber) {
        return DAY_NAMES.getOrDefault(dayNumber, "Invalid day");
    }
}

三、使用枚举

  1. 优化前
java 复制代码
public static String getStatusDescription(int statusCode) {
    if (statusCode == 200) {
        return "OK";
    } else if (statusCode == 404) {
        return "Not Found";
    } else if (statusCode == 500) {
        return "Internal Server Error";
    } else {
        return "Unknown Status";
    }
}
  1. 优化后
java 复制代码
public enum HttpStatus {
    OK(200, "OK"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_ERROR(500, "Internal Server Error");

    private final int code;
    private final String description;

    HttpStatus(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public static String getDescription(int code) {
        for (HttpStatus status : values()) {
            if (status.code == code) {
                return status.description;
            }
        }
        return "Unknown Status";
    }
}

String description = HttpStatus.getDescription(statusCode);

四、使用函数式编程

1、JS 实例实操
js 复制代码
const conditions = [
    { test: (x) => x < 0, result: "负值" },
    { test: (x) => x === 0, result: "零" },
    { test: (x) => x > 0, result: "正值" },
];

function evaluate(x) {
    return conditions.find((cond) => cond.test(x)).result;
}
2、Java 实例实操
java 复制代码
interface Condition {
    boolean test(int x);

    String getResult();
}

public static String evaluate(int x) {
    List<Condition> conditions = Arrays.asList(
            new Condition() {
                @Override
                public boolean test(int x) {
                    return x < 0;
                }

                @Override
                public String getResult() {
                    return "负值";
                }
            },
            new Condition() {
                @Override
                public boolean test(int x) {
                    return x == 0;
                }

                @Override
                public String getResult() {
                    return "零";
                }
            },
            new Condition() {
                @Override
                public boolean test(int x) {
                    return x > 0;
                }

                @Override
                public String getResult() {
                    return "正值";
                }
            }
    );

    Optional<Condition> matched = conditions.stream()
            .filter(cond -> cond.test(x))
            .findFirst();

    return matched.isPresent() ? matched.get().getResult() : "未知";
}
相关推荐
Lhappy嘻嘻27 分钟前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
胡萝卜术38 分钟前
从API调用到手写LRU:力扣146「LRU缓存」的哈希表+双向链表终极进化之路
前端·javascript·面试
科技道人41 分钟前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
伊玛目的门徒1 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
逝水无殇3 小时前
C# 异常处理详解
开发语言·后端·c#
懒鸟一枚4 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
玖玥拾5 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
铅笔侠_小龙虾5 小时前
Rust 学习目录
开发语言·学习·rust
我命由我123455 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑5 小时前
Sentinel安装
java·后端·微服务