You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

if语句的替代方案有哪些?除switch case外如何简化多条件判断

简化Java条件判断的替代方案(除switch外)

针对你给出的代码,这里提供几种比多if/switch更简洁、易维护的替代方案:

1. 使用Map映射(最常用)

把字符串和对应的UUID直接存入Map,通过键值对直接获取结果,代码简洁且易于扩展:

// 可以把Map定义为类的静态成员,避免每次调用都初始化
private static final Map<String, String> FOLDER_UUID_MAP = Map.of(
    "birds", birdPFUuid,
    "dogs", dogPFUuid,
    "cats", catPFUuid,
    "vehicles", vehiclesPFUuid
);

public void check(String name) {
    // 直接通过key获取,不存在则用默认空字符串
    String parentFolder = FOLDER_UUID_MAP.getOrDefault(name, "");
}

注:如果你的matches是需要正则匹配而非精确字符串匹配,可以改用循环遍历Map的key,用key.matches(name)来匹配,但精确匹配优先用equals,性能更好。

2. 使用枚举类

如果后续可能需要给每个类型添加更多属性或行为,枚举类是更规范的选择:

enum FolderType {
    BIRDS("birds", birdPFUuid),
    DOGS("dogs", dogPFUuid),
    CATS("cats", catPFUuid),
    VEHICLES("vehicles", vehiclesPFUuid);

    private final String name;
    private final String uuid;

    FolderType(String name, String uuid) {
        this.name = name;
        this.uuid = uuid;
    }

    // 根据name获取对应的枚举实例
    public static FolderType getByName(String name) {
        for (FolderType type : values()) {
            if (type.name.equals(name)) {
                return type;
            }
        }
        return null;
    }
}

public void check(String name) {
    FolderType type = FolderType.getByName(name);
    String parentFolder = type != null ? type.uuid : "";
}

3. 策略模式(适合复杂逻辑场景)

如果每个条件分支后续需要执行的逻辑不止赋值,而是有更多业务操作,策略模式可以让代码更符合开闭原则:

// 定义策略接口
interface FolderStrategy {
    String getParentFolderUuid();
}

// 实现各个策略类
class BirdsFolderStrategy implements FolderStrategy {
    @Override
    public String getParentFolderUuid() {
        return birdPFUuid;
    }
}

class DogsFolderStrategy implements FolderStrategy {
    @Override
    public String getParentFolderUuid() {
        return dogPFUuid;
    }
}

class CatsFolderStrategy implements FolderStrategy {
    @Override
    public String getParentFolderUuid() {
        return catPFUuid;
    }
}

class VehiclesFolderStrategy implements FolderStrategy {
    @Override
    public String getParentFolderUuid() {
        return vehiclesPFUuid;
    }
}

// 用Map管理策略实例
private static final Map<String, FolderStrategy> STRATEGY_MAP = Map.of(
    "birds", new BirdsFolderStrategy(),
    "dogs", new DogsFolderStrategy(),
    "cats", new CatsFolderStrategy(),
    "vehicles", new VehiclesFolderStrategy()
);

public void check(String name) {
    FolderStrategy strategy = STRATEGY_MAP.getOrDefault(name, () -> "");
    String parentFolder = strategy.getParentFolderUuid();
}

内容的提问来源于stack exchange,提问作者CvMr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:05:25