gpt4 book ai didi

java - 将多个选项与特定条件相匹配

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:14 29 4
gpt4 key购买 nike

我想要实现的是将多个 boolean 选项与匹配条件相匹配。到目前为止,这是我的设计。我对此并不满意。如何有效地编写与某个条件匹配的多个选项?或者有多个选项是主要的代码味道吗?

class Condition 
{
Boolean a; // Optional
Boolean b; // Optional
Boolean c; // Optional
boolean d; // mandatory

Condition(Boolean a, Boolean b, Boolean c, boolean d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}

public boolean matches(Boolean a, Boolean b, Boolean c, boolean b)
{
return (a == null || this.a == a)
&& (b == null || this.b == b)
&& (c == null || this.c == c)
&& (this.b == b);
}

public static void main(String args[]) {
Condition c1 = new Condition(true, true, null, true);
Condition c2 = new Condition(null, null, false, false);
Condition c3 = new Condition(false, true, null, true);
Condition[] conditions = new Condition[]{c1,c2,c3};

for (Condition con : conditions) {
Boolean a = someTestLogic1(...);
Boolean b = someTestLogic2(...);
Boolean c = someTestLogic3(...);
boolean d = someTestLogicMandatory(...);

if (con.matches(a,b,c,d)) {
// found the matching condition
return con;
}
}
}
}

最佳答案

I suspect there is a more efficient (speed) and elegant way (less verbose) of achieving the same with lesser Constructor params, and also I don't like the looping of all conditions and breaking to find the first matching one.

您当前的代码显然很少有问题,如下所示:

(1) 传递 null o 满足构造函数调用以创建实例,这不是一个好的做法。

(2) 即使您正在检查同一类型的两个对象的相等性,也不使用 equals() 方法。

因此,针对上述问题的答案如下:

(1) 您可以使用Builder pattern解决第一个问题

(2) 显然,您需要重写 java.lang.Object 中的 equals()hashcode() 方法来匹配两个对象的相等性。

<小时/>

重要的一点是,这两种解决方案可能无法完全解决您的冗长问题,即避免 if 检查或条件(因为它们是您的核心逻辑的一部分)。但是,这些更正将引导您走向正确的方向,并使您的代码更加结构化(因此不那么困惑)并且易于阅读和维护。

关于java - 将多个选项与特定条件相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43377739/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com