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

如何重构Java中嵌套过多if-else的数据库校验插入代码

重构多层嵌套if-else的数据库校验插入代码方案

你的这段代码核心是多轮「校验记录存在性→不存在则执行插入→验证插入结果」的业务逻辑,但多层if-else嵌套导致代码可读性极差、维护成本高,以下是几种实用的重构方案:

1. 提前返回(Guard Clause)消除嵌套

将所有异常分支(记录已存在、插入失败、数量不匹配等)放在代码最前端,触发时直接设置响应并结束当前逻辑,让主业务逻辑保持在最外层,彻底消除深层缩进。

示例改造片段:

CheckCertRecordDao checkCertHistRecordDao = new CheckCertRecordDaoImpl(connection);
int countCertRecord = checkCertHistRecordDao.countCertHistRecordBySerialNo(certIdList);
if (countCertRecord != 0) {
    response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
    response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
    Als.audit(AlsAction.EXCEPTION, "countCertRecord =/= 0, existing the cert hist record already!");
    return; // 提前返回,不再执行后续逻辑
}

InsertCertRecordDao insertCertHistRecordDao = new InsertCertRecordDaoImpl(connection);
insertedCertHist = insertCertHistRecordDao.insertCertHistRecord(certIdList);
if (!insertedCertHist) {
    response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
    response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
    Als.audit(AlsAction.EXCEPTION, "Inserted cert hist record with error!!");
    return;
}

countCertRecord = checkCertHistRecordDao.countCertHistRecordBySerialNo(certIdList);
if (countCertRecord != certIdList.size()) {
    response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
    response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
    Als.audit(AlsAction.EXCEPTION, "Number of inserted cert hist record is [NOT] matched with the certIdList");
    return;
}
Als.audit(AlsAction.EXCEPTION, "Number of inserted cert hist record is matched with the certIdList!");

// 后续Mode、ConnClient等逻辑同样用提前返回处理

2. 按业务实体提取独立方法

把每个实体(Cert、Mode、ConnClient、ConnInfo)的「校验-插入-验证」逻辑拆分为单独的方法,每个方法只负责单一实体的业务,让主流程变成清晰的方法调用链。

示例方法提取:

private boolean insertCertIfNotExists(Connection connection, List<String> certIdList, SirResponse response) {
    CheckCertRecordDao checkDao = new CheckCertRecordDaoImpl(connection);
    int count = checkDao.countCertHistRecordBySerialNo(certIdList);
    if (count != 0) {
        response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
        response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
        Als.audit(AlsAction.EXCEPTION, "countCertRecord =/= 0, existing the cert hist record already!");
        return false;
    }

    InsertCertRecordDao insertDao = new InsertCertRecordDaoImpl(connection);
    boolean inserted = insertDao.insertCertHistRecord(certIdList);
    if (!inserted) {
        response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
        response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
        Als.audit(AlsAction.EXCEPTION, "Inserted cert hist record with error!!");
        return false;
    }

    count = checkDao.countCertHistRecordBySerialNo(certIdList);
    if (count != certIdList.size()) {
        response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
        response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
        Als.audit(AlsAction.EXCEPTION, "Number of inserted cert hist record is [NOT] matched with the certIdList");
        return false;
    }
    Als.audit(AlsAction.EXCEPTION, "Number of inserted cert hist record is matched with the certIdList!");
    return true;
}

// 同理实现insertModeIfNotExists、insertConnClientIfNotExists等方法

主流程就会变得非常简洁:

if (!insertCertIfNotExists(connection, certIdList, response)) return;
if (!insertModeIfNotExists(connection, modeId, response)) return;
if (!insertConnClientIfNotExists(connection, clientIdList, response)) return;
if (!insertConnInfoIfNotExists(connection, infoIdList, response)) return;

3. 抽象通用逻辑,封装模板方法

所有实体的逻辑都是「校验存在→执行插入→验证结果」的标准化流程,可以抽象出通用模板,通过接口或回调复用流程,避免重复代码。

示例通用模板:

@FunctionalInterface
interface ExistenceChecker<T> {
    int check(T param);
}

@FunctionalInterface
interface RecordInserter<T> {
    boolean insert(T param);
}

private <T> boolean processRecord(Connection connection, 
                                  T param, 
                                  int expectedCount,
                                  ExistenceChecker<T> checker,
                                  RecordInserter<T> inserter,
                                  String existMsg,
                                  String insertFailMsg,
                                  String countMismatchMsg,
                                  String successMsg,
                                  SirResponse response) {
    int count = checker.check(param);
    if (count != 0) {
        response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
        response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
        Als.audit(AlsAction.EXCEPTION, existMsg);
        return false;
    }

    boolean inserted = inserter.insert(param);
    if (!inserted) {
        response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
        response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
        Als.audit(AlsAction.EXCEPTION, insertFailMsg);
        return false;
    }

    count = checker.check(param);
    if (count != expectedCount) {
        response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
        response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
        Als.audit(AlsAction.EXCEPTION, countMismatchMsg);
        return false;
    }
    Als.audit(AlsAction.EXCEPTION, successMsg);
    return true;
}

调用模板处理Cert实体:

boolean certSuccess = processRecord(connection,
                                   certIdList,
                                   certIdList.size(),
                                   param -> new CheckCertRecordDaoImpl(connection).countCertHistRecordBySerialNo(param),
                                   param -> new InsertCertRecordDaoImpl(connection).insertCertHistRecord(param),
                                   "countCertRecord =/= 0, existing the cert hist record already!",
                                   "Inserted cert hist record with error!!",
                                   "Number of inserted cert hist record is [NOT] matched with the certIdList",
                                   "Number of inserted cert hist record is matched with the certIdList!",
                                   response);
if (!certSuccess) return;

4. 用异常替代重复的错误状态判断

自定义业务异常(如RecordExistsException、InsertFailedException、CountMismatchException),将错误处理逻辑集中到外层的try-catch块,避免在每个分支重复设置response。

示例改造:

try {
    processCert(connection, certIdList);
    processMode(connection, modeId);
    processConnClient(connection, clientIdList);
    processConnInfo(connection, infoIdList);
} catch (BusinessException e) {
    response.setStatusCode(SirResponse.ERROR_UNKNOWN_CD);
    response.setResultMsgByCode(SirResponse.ERROR_UNKNOWN_CD);
    Als.audit(AlsAction.EXCEPTION, e.getMessage());
}

// 每个process方法内部抛出异常
private void processCert(Connection connection, List<String> certIdList) throws BusinessException {
    CheckCertRecordDao checkDao = new CheckCertRecordDaoImpl(connection);
    int count = checkDao.countCertHistRecordBySerialNo(certIdList);
    if (count != 0) {
        throw new BusinessException("countCertRecord =/= 0, existing the cert hist record already!");
    }

    InsertCertRecordDao insertDao = new InsertCertRecordDaoImpl(connection);
    boolean inserted = insertDao.insertCertHistRecord(certIdList);
    if (!inserted) {
        throw new BusinessException("Inserted cert hist record with error!!");
    }

    count = checkDao.countCertHistRecordBySerialNo(certIdList);
    if (count != certIdList.size()) {
        throw new BusinessException("Number of inserted cert hist record is [NOT] matched with the certIdList");
    }
    Als.audit(AlsAction.EXCEPTION, "Number of inserted cert hist record is matched with the certIdList!");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:42:53