- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想要实现的是将多个 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/
现在我正在尝试实现 flash programming specification对于 PIC32MX。我正在使用 PIC32MX512L 和 PIC32MX512H。 PIC32MX512L最终必须
我是一名优秀的程序员,十分优秀!