【问题标题】:How to avoid lots of if else conditions with some conditions inside if else如何避免大量 if else 条件和 if else 内部的一些条件
【发布时间】:2021-06-23 16:45:23
【问题描述】:

我正在努力避免其他情况,你们可以帮帮我吗?

if (getFromDate() != null && getToDate() != null && getBranchId() != null && getServiceGroupId() != null) {

        return something;

    } else if (getFromDate() != null && getToDate() != null && getBranchId() != null && getServiceGroupId() == null) {

        return something;

    } else if (getFromDate() != null && getToDate() != null && getServiceGroupId() != null && getBranchId() == null) {

        return something;

    } else if (getServiceGroupId() != null && getBranchId() != null && getFromDate() == null && getToDate() == null) {

        return something;

    } else if (getServiceGroupId() == null && getBranchId() == null && getFromDate() != null && getToDate() != null) {

        return something;
    } else if (getFromDate() == null && getToDate() == null && getBranchId() == null && getServiceGroupId() != null) {

        return something;
    } else if (getFromDate() == null && getToDate() == null && getBranchId() != null && getServiceGroupId() == null) {

        return something;

    } else {
        return something;
    }

【问题讨论】:

  • 您问,好像我们知道您的 ifs 和 elses 背后的逻辑...您可以首先解释您要实现的目标,然后我们可能会提供帮助你
  • 也许他想根据条件 where 子句做一些 sql 搜索?
  • 为什么要避开if ... else
  • 没有什么理由,结果总是“某事” 更严重的是:巧妙的重新排序/分组可以帮助很多,您可以使用方法重载隐藏选择,或者转换/then/else 进入表查找计算,但其核心仍然是 if..else

标签: java spring-boot optimization


【解决方案1】:

您可以使用Stream.allMatch(x -> x == null) 检查来自不同或相似类型的多个null 值。使用Stream.of(T... values) 声明Stream 变量(或数组)。

最好在某个函数上声明boolean foo(T... varargs)

【讨论】:

    【解决方案2】:

    我在您的代码中看到以下模式:

    您有一组布尔条件(某些值为 null 与非 null)并希望根据这些条件的特定真/假组合返回不同的值。

    如果您在多个地方遇到这种模式,可能值得引入一个支持类。我们称它为MultiBoolean,这样你就可以写:

    MultiBoolean nullCombinations = new MultiBoolean(
        getFromDate() == null,
        getToDate() == null,
        getBranchId() == null,
        getServiceGroupId() == null);
    if (nullCombinations.matches(false, false, false, false) {
        return something;
    } else if (nullCombinations.matches(false, false, false, true) {
        return something;
    } else if (...) {
        // and so on
    

    该类可能大致如下:

    public class MultiBoolean {
        private boolean[] conditions;
        public MultiBoolean(boolean... conditions) {
            this.conditions = conditions;
        }
        public boolean matches(boolean... pattern) {
            return Arrays.equals(conditions, pattern);
        }
    }
    

    免责声明:我没有测试它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-27
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多