当前位置: 首页 > news >正文

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

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

一、使用策略模式

1、JS 实例实操
  1. 优化前
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. 优化后
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. 优化前
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. 优化后
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. 优化前
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. 优化后
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. 优化前
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. 优化后
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. 优化前
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. 优化后
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 实例实操
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 实例实操
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() : "未知";
}
http://www.sczhlp.com/news/12681/

相关文章:

  • ts基础入门d2 pixpin截图
  • 打印沙漏
  • 树上 DP(树形 DP 换根 DP)
  • 读书笔记:数据库的保存与撤销:程序员必须懂的提交与回滚原理
  • 忽有故人心上过,回首山河已是秋
  • 排卡
  • windows安装ubuntu 22
  • RPC框架的优化
  • 面向对象(三大特点→内部类)+异常
  • 若干背包模型 powered by ddxrS
  • Makefile变量赋值操作符详解:`:=`与`+=`的区别与使用
  • UAC
  • 鸽巢
  • yny组合计数
  • unixODBC编程(八)使用滚动游标
  • unixODBC编程(九)分片查询长数据
  • 题解 P3380【模板】树套树(莫队套分块)
  • unixODBC编程(四)插入数据
  • 考研题:假设二叉树采用二叉链存储结构,设计一个算法,计算该二叉树中结点的总数。
  • 2.11 rt-thread实操 esp8266 +webserver
  • unxiODBC编程(五)错误处理
  • Kotlin基础
  • JAVA学习(8月15号)
  • 硬币购物
  • Docker知识点2 - Charon
  • unixODBC编程(二)连接数据库
  • 河南萌新联赛2025第(五)场题解:I J(LCA)
  • Ruby 和 Tesseract OCR 实现验证码识别
  • Kotlin 和 Tesseract OCR 实现验证码识别
  • ReasonRank:从关键词匹配到逻辑推理,排序准确性大幅超越传统方法