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

重构含嵌套条件分支的Java代码时返回值异常问题求助

解决重构后逻辑不符的问题

你的核心问题在于:重构后的getToken方法中,进入if或else分支后直接返回子函数的结果,导致子函数返回null时(即嵌套条件不满足),直接返回null,跳过了原逻辑中最后的拼接步骤。要修复这个问题,需要先判断子函数的返回值是否有效,只有有效时才提前返回,否则继续执行后续逻辑。

修改后的代码实现

方案1:通过null判断保留原逻辑

public String getAString(A a) {
  if (a.getBow().equals("3")) {
    return a.getBow();
  } else if (a.getBow().equals("4")) {
    return a.getMeow();
  }
  return null;
}

public String getBString(B b) {
  if (b.getBow().equals("2")) {
    return b.getBow();
  } else if (b.getBow().equals("10")) {
    return b.getMeow();
  }
  return null;
}

public String getToken() {
  A a = new A();
  B b = new B();
  String result = null;
  if (a.getMeow().equals("2")) {
    result = getAString(a);
  } else {
    result = getBString(b);
  }
  // 子函数返回有效结果才提前返回,否则执行最后的拼接逻辑
  if (result != null) {
    return result;
  }
  String meow = a.getMeow();
  meow += "2";
  return meow;
}

方案2:使用Optional优化空值判断(现代Java风格)

import java.util.Optional;

public Optional<String> getAString(A a) {
  if (a.getBow().equals("3")) {
    return Optional.of(a.getBow());
  } else if (a.getBow().equals("4")) {
    return Optional.of(a.getMeow());
  }
  return Optional.empty();
}

public Optional<String> getBString(B b) {
  if (b.getBow().equals("2")) {
    return Optional.of(b.getBow());
  } else if (b.getBow().equals("10")) {
    return Optional.of(b.getMeow());
  }
  return Optional.empty();
}

public String getToken() {
  A a = new A();
  B b = new B();
  Optional<String> result = Optional.empty();
  if (a.getMeow().equals("2")) {
    result = getAString(a);
  } else {
    result = getBString(b);
  }
  // 有有效结果则返回,否则执行拼接逻辑
  return result.orElseGet(() -> a.getMeow() + "2");
}

重要提醒

原代码中用==比较字符串是错误的,Java中必须用equals()方法比较字符串内容,否则会因为字符串对象引用不同导致判断逻辑失效,上面的代码已经统一修正了这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:37:49